ProgramingTip

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

bestdevel 2020. 12. 29. 07:41
반응형

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


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는 내 몽구스 CommentSchema의 사용자 참조입니다. 현재는 사용자 ID 만 제공하고 암호 및 솔트 필드를 모든 사용자 데이터로 채워야합니다.

사람들이 요청한 스키마는 다음과 가변적입니다.

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와 @ chris-foster가 맞습니다!

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

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

반응형