本文介绍了在猫鼬中引用另一个模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如果我有两个模式,例如:
if I have two schemas like:
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}],
});
我试图像上面的例子一样将它们连接在一起,但我不知道如何去做.最终,如果我能做这样的事情,我的生活就会变得很轻松
I tried to connect them together like the example above but I couldn't figure out how to do it. Eventually, if I can do something like this it would make my life very easy
var profilePic = Post.postedBy.profilePic
推荐答案
听起来 populate 方法正是您要找的.首先对您的帖子架构进行小幅更改:
It sounds like the populate method is what your looking for. First make small change to your post schema:
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);
然后,当您进行查询时,您可以像这样填充引用:
Then, when you make your query, you can populate references like this:
Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
// do stuff with post
});
这篇关于在猫鼬中引用另一个模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!