programing

하위 문서를 만든 후 몽구스에 채우는 방법은 무엇입니까?

minimums 2023. 5. 3. 20:53
반응형

하위 문서를 만든 후 몽구스에 채우는 방법은 무엇입니까?

나는 item.comments 목록에 코멘트를 추가합니다.응답에 출력하기 전에 comment.created_by 사용자 데이터를 가져와야 합니다.이거 어떻게 해야 돼요?

    Item.findById(req.param('itemid'), function(err, item){
        var comment = item.comments.create({
            body: req.body.body
            , created_by: logged_in_user
        });

        item.comments.push(comment);

        item.save(function(err, item){
            res.json({
                status: 'success',
                message: "You have commented on this item",

//how do i populate comment.created_by here???

                comment: item.comments.id(comment._id)
            });
        }); //end item.save
    }); //end item.find

여기 res.json 출력에 comment.created_by 필드를 입력해야 합니다.

                comment: item.comments.id(comment._id)

comment.created_by는 my mongoose CommentSchema의 사용자 참조입니다.현재는 사용자 ID만 제공하고 있으며, 비밀번호와 salt 필드를 제외한 모든 사용자 데이터로 채워야 합니다.

사람들이 질문한 대로 스키마는 다음과 같습니다.

var CommentSchema = new Schema({
    body          : { type: String, required: true }
  , created_by    : { type: Schema.ObjectId, ref: 'User', index: true }
  , created_at    : { type: Date }
  , updated_at    : { type: Date }
});

var ItemSchema = new Schema({
    name    : { type: String, required: true, trim: true }
  , created_by  : { type: Schema.ObjectId, ref: 'User', index: true }
  , comments  : [CommentSchema]
});

참조된 하위 문서를 채우려면 ID가 참조하는 문서 모음을 명시적으로 정의해야 합니다.created_by: { type: Schema.Types.ObjectId, ref: 'User' }).

이 참조가 정의되어 있고 스키마도 잘 정의되어 있기 때문에 이제 다음을 호출할 수 있습니다.populate평소와 같이(예:populate('comments.created_by'))

개념 증명 코드:

// Schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
  name: String
});

var CommentSchema = new Schema({
  text: String,
  created_by: { type: Schema.Types.ObjectId, ref: 'User' }
});

var ItemSchema = new Schema({
   comments: [CommentSchema]
});

// Connect to DB and instantiate models    
var db = mongoose.connect('enter your database here');
var User = db.model('User', UserSchema);
var Comment = db.model('Comment', CommentSchema);
var Item = db.model('Item', ItemSchema);

// Find and populate
Item.find({}).populate('comments.created_by').exec(function(err, items) {
    console.log(items[0].comments[0].created_by.name);
});

마지막으로 유의하십시오.populate는 쿼리에서만 작동하므로 먼저 항목을 쿼리로 전달한 다음 호출해야 합니다.

item.save(function(err, item) {
    Item.findOne(item).populate('comments.created_by').exec(function (err, item) {
        res.json({
            status: 'success',
            message: "You have commented on this item",
            comment: item.comments.id(comment._id)
        });
    });
});

원래 답변이 작성된 이후에 변경되었을 수도 있지만, 이제 추가 findOne을 실행하지 않고도 모델 채우기 기능을 사용할 수 있는 것 같습니다.http://mongoosejs.com/docs/api.html#model_Model.populate 을 참조하십시오.findOne과 마찬가지로 저장 핸들러 내에서 이 기능을 사용할 수 있습니다.

@user1417684와 @http-session이 맞습니다!

작업 코드에서 발췌(오류 처리 없음):

var SubItemModel = mongoose.model('subitems', SubItemSchema);
var ItemModel    = mongoose.model('items', ItemSchema);

var new_sub_item_model = new SubItemModel(new_sub_item_plain);
new_sub_item_model.save(function (error, new_sub_item) {

  var new_item = new ItemModel(new_item);
  new_item.subitem = new_sub_item._id;
  new_item.save(function (error, new_item) {
    // so this is a valid way to populate via the Model
    // as documented in comments above (here @stack overflow):
    ItemModel.populate(new_item, { path: 'subitem', model: 'subitems' }, function(error, new_item) {
      callback(new_item.toObject());
    });
    // or populate directly on the result object
    new_item.populate('subitem', function(error, new_item) {
      callback(new_item.toObject());
    });
  });

});

저도 같은 문제에 직면했지만 몇 시간 동안 노력한 끝에 해결책을 찾았습니다.외부 플러그인을 사용하지 않을 수 있습니다:)

applicantListToExport: function (query, callback) {
  this
   .find(query).select({'advtId': 0})
   .populate({
      path: 'influId',
      model: 'influencer',
      select: { '_id': 1,'user':1},
      populate: {
        path: 'userid',
        model: 'User'
      }
   })
 .populate('campaignId',{'campaignTitle':1})
 .exec(callback);
}

언급URL : https://stackoverflow.com/questions/13026486/how-to-populate-a-sub-document-in-mongoose-after-creating-it

반응형