Mongoose/MongoDB中嵌套模式的正确模式是什么? [英] What is the proper pattern for nested schemas in Mongoose/MongoDB?
问题描述
执行以下操作对我来说似乎合乎逻辑:
It seems logical to me to do something like the following:
var AvatarSchema = new Mongoose.Schema({
type: String,
url: String
});
var UserSchema = new Mongoose.Schema({
avatars: [AvatarSchema],
email: String,
name: String,
salt: String,
token: String
});
var ThinUserSchema = new Mongoose.Schema({
avatars: [AvatarSchema],
email: String,
firstname: String,
lastname: String,
});
var QuestionSchema = new Mongoose.Schema({
question: String,
users: [ThinUserSchema]
});
然后再说. . .执行以下操作:
Then later on. . .do something like the following:
var question = new Question({
question: 'Wut?',
users: users //where users is an array of instances of a user model of the UserSchema
});
在这里,我希望问题的用户部分填充有头像,电子邮件,名字和姓氏. . .但是,由于用户/头像已经具有_id,因此这些名称不会保留.
Here I would expect the users section of the question to be populated with avatars, emails, firstnames and lastnames. . .however since the users/avatars already have _id, these are not persisted.
- 从用户/头像中删除每个_id似乎很愚蠢.
- 显式设置每个用户/头像似乎效率低下.
- 切换到混合类型,将所有内容放入其中,并且需要markModified.
这些模式的正确模式是什么?
What is the proper pattern for these sorts of schemas?
谢谢!
推荐答案
我相信您的假设是正确的,在Mongoose中称为嵌入式文档,这是Mongoose文档中的示例.
I believe you are correct in your assumptions, it's called Embedded documents in Mongoose, here is the example from the Mongoose documentation.
var Comments = new Schema({
title : String
, body : String
, date : Date
});
var BlogPost = new Schema({
author : ObjectId
, title : String
, body : String
, date : Date
, comments : [Comments]
, meta : {
votes : Number
, favs : Number
}
});
mongoose.model('BlogPost', BlogPost);
免责声明:我不一定要在项目前加逗号!
Disclaimer: I wouldn't necessarily put the comma before the items!
这篇关于Mongoose/MongoDB中嵌套模式的正确模式是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!