[MONGODB] 어떻게 그것을 만든 후 몽구스의 하위 문서를 채우는?
MONGODB어떻게 그것을 만든 후 몽구스의 하위 문서를 채우는?
나는 item.comments 목록에 주석을 추가하고있다. 나는 응답 I 출력을하기 전에 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]
});
해결법
-
==============================
1.참조 하위 문서를 채우기 위해, 당신은 명시 적으로 문서 컬렉션을 정의 할 필요가있는 상태 (CREATED_BY이 (가) 작성한 같은 : {유형 : Schema.Types.ObjectId, REF : '사용자'})에 ID 참조.
참조 하위 문서를 채우기 위해, 당신은 명시 적으로 문서 컬렉션을 정의 할 필요가있는 상태 (CREATED_BY이 (가) 작성한 같은 : {유형 : Schema.Types.ObjectId, REF : '사용자'})에 ID 참조.
이 참조가 정의 감안할 때 스키마 달리 잘 값으로 정의된다, 당신은 지금 막 평소와 같이 채우기를 호출 할 수 있습니다 (예를 들어, 채우기 ( '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); });
마지막으로 당신이 먼저 전화를 다음 쿼리로 항목을 통과해야합니다 그래서 채우기 쿼리에 대해서만 작동합니다 :
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) }); }); });
-
==============================
2.원래 답이 기록 된 이후이 변경되었을 수 있지만, 당신은 지금 여분 findOne을 실행하지 않고이 작업을 수행 할 모델을 채우기 기능을 사용할 수 있습니다 것 같습니다. 참조 : http://mongoosejs.com/docs/api.html#model_Model.populate합니다. 당신은 findOne이처럼 저장 핸들러 내부에서이를 사용하고자하는 것입니다.
원래 답이 기록 된 이후이 변경되었을 수 있지만, 당신은 지금 여분 findOne을 실행하지 않고이 작업을 수행 할 모델을 채우기 기능을 사용할 수 있습니다 것 같습니다. 참조 : http://mongoosejs.com/docs/api.html#model_Model.populate합니다. 당신은 findOne이처럼 저장 핸들러 내부에서이를 사용하고자하는 것입니다.
-
==============================
3.@ user1417684 및 @ 크리스 - 수양은 옳다!
@ user1417684 및 @ 크리스 - 수양은 옳다!
(오류 처리없이) 코드를 작업에서 발췌 :
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()); }); }); });
-
==============================
4.저도 같은 문제에 직면하지만, 노력의 시간 후에 나는 solution.It는 외부 플러그인을 사용하지 않고 할 수 있습니다 찾을 수 있습니다 :
저도 같은 문제에 직면하지만, 노력의 시간 후에 나는 solution.It는 외부 플러그인을 사용하지 않고 할 수 있습니다 찾을 수 있습니다 :
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); }
from https://stackoverflow.com/questions/13026486/how-to-populate-a-sub-document-in-mongoose-after-creating-it by cc-by-sa and MIT license
'MONGODB' 카테고리의 다른 글
[MONGODB] 자동 MongoDB의에서 삭제 된 공간을 압축? (0) | 2019.12.05 |
---|---|
[MONGODB] 어떻게하여 MongoDB에서이 스키마를 구현해야합니까? (0) | 2019.12.05 |
[MONGODB] C 번호와 MongoDB를 GridFs, 어떻게 이미지와 같은 파일을 저장하려면? (0) | 2019.12.05 |
[MONGODB] MongoDB를에 개체의 배열에서 검색하는 방법 (0) | 2019.12.05 |
[MONGODB] JSON 파일의 Mongoimport (0) | 2019.12.05 |