mongodb 在猫鼬中引用另一个模式
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18001478/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Referencing another schema in Mongoose
提问by Gorkem Yurtseven
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
回答by nicksweet
It sounds like the populate method is what your looking for. First make small change to your post schema:
听起来 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}],
});
Then make your model:
然后制作你的模型:
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
});
回答by fino
Addendum: No one mentioned "Populate" --- it is very much worth your time and money looking at Mongooses Populate Method : Also explains cross documents referencing
附录:没有人提到“填充”——看猫鼬填充方法非常值得你花时间和金钱:还解释了交叉文档引用
回答by D. Lowe
Late reply, but adding that Mongoose also has the concept of Subdocuments
回复晚了,但补充说Mongoose也有子文档的概念
With this syntax, you should be able to reference your userSchema
as a type in your postSchema
like so:
使用此语法,您应该能够像这样引用您userSchema
的类型postSchema
:
var userSchema = new Schema({
twittername: String,
twitterID: Number,
displayName: String,
profilePic: String,
});
var postSchema = new Schema({
name: String,
postedBy: userSchema,
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Note the updated postedBy
field with type userSchema
.
请注意postedBy
带有 type的更新字段userSchema
。
This will embed the user object within the post, saving an extra lookup required by using a reference. Sometimes this could be preferable, other times the ref/populate route might be the way to go. Depends on what your application is doing.
这会将用户对象嵌入帖子中,从而节省使用引用所需的额外查找。有时这可能更可取,其他时候 ref/populate 路线可能是要走的路。取决于您的应用程序在做什么。