Gor*_*ven 96 javascript mongoose mongodb
如果我有两个模式,如:
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}],
});
Run Code Online (Sandbox Code Playgroud)
我尝试将它们连接在一起,就像上面的例子,但我无法弄清楚如何做到这一点.最终,如果我可以做这样的事情,那将使我的生活变得非常轻松
var profilePic = Post.postedBy.profilePic
Run Code Online (Sandbox Code Playgroud)
nic*_*eet 160
听起来像填充方法就是你要找的东西.首先对您的帖子架构进行小的更改:
var postSchema = new Schema({
name: String,
postedBy: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
dateCreated: Date,
comments: [{body:"string", by: mongoose.Schema.Types.ObjectId}],
});
Run Code Online (Sandbox Code Playgroud)
然后制作你的模特:
var Post = mongoose.model('Post', postSchema);
Run Code Online (Sandbox Code Playgroud)
然后,当您进行查询时,可以填充这样的引用:
Post.findOne({_id: 123})
.populate('postedBy')
.exec(function(err, post) {
// do stuff with post
});
Run Code Online (Sandbox Code Playgroud)
fin*_*ino 18
附录:没有人提到"填充" - 非常值得你花时间和金钱看Mongooses Populate方法:也解释了交叉文件引用
http://mongoosejs.com/docs/populate.html
小智 8
回复晚了,但补充说Mongoose也有子文档的概念
使用此语法,您应该能够像这样将您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}],
});
Run Code Online (Sandbox Code Playgroud)
请注意postedBy
带有 type的更新字段userSchema
。
这会将用户对象嵌入帖子中,从而节省使用引用所需的额外查找。有时这可能更可取,其他时候 ref/populate 路线可能是要走的路。取决于您的应用程序在做什么。
归档时间: |
|
查看次数: |
101513 次 |
最近记录: |