2016-03-06 61 views
0

很抱歉的模糊冠军,但我想要做的是以下几点: 我有2种獴型号:帖子和用户(可以是帖子的作者)猫鼬Model.find - >编辑 - >回调?

const Post = new Schema({ 
    title: {type: String, required: true, unique: true}, 
    content: {type: String, required: true}, 
    date_created: {type: Date, required: true, default: Date.now}, 
    authorId: {type: String, required: true},    // ObjectId 
    author: {type: Schema.Types.Mixed}, 
    page: {type: Boolean, required: true, default: false} 
}); 

post.find()
猫鼬发送查询的MongoDB
的MongoDB返回文档
中间件检索基础上,authorId财产笔者
Add找到用户的帖子author
post.find callback

这可能吗?

回答

1

是,mongoose document references and population会为你做到这一点。

const Post = new Schema({ 
    // ... 
    author: {type: mongoose.Schema.Types.ObjectId, required: true, ref: "User"} 
}); 

ref: "User"告诉Mongoose使用“User”类型作为对象类型。确保你有一个用Mongoose定义的“用户”模型,否则这将失败。

加载完整的对象图,使用查询的populate方法:


Post 
    .findOne(/* ... */) 
    .populate('author') 
    .exec(function (err, story) { 
    // ... 

    }); 

P.S.我在Screencast Package中涵盖了这个和更多。

+0

谢谢! 这的确有诀窍! ^^ 代码现在工作:) '常量体=收率this.Model.find() .populate( 'AUTHORID') .lean();' – CreasolDev