如果我有两个模式,如:
var userSchema = new Schema({ twittername: String, twitterID: Number, displayName: String, profilePic: String, }); var User = mongoose.model('User') var postSchema = new Schema({ name: String, postedBy: User, //User Model Type dateCreated: Date, comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}], });
我试图像上面的示例一样将它们连接在一起,但是我不知道该怎么做。最终,如果我可以做这样的事情,那将使我的生活变得很轻松
var profilePic = Post.postedBy.profilePic
听起来好像populate方法是您想要的。首先,对您的发布架构进行少量更改:
var postSchema = new Schema({ name: String, postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'}, dateCreated: Date, comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}], });
然后建立您的模型:
var Post = mongoose.model('Post', postSchema);
然后,当您进行查询时,可以像这样填充引用:
Post.findOne({_id: 123}) .populate('postedBy') .exec(function(err, post) { // do stuff with post });