[英]Mongoose one-to-many - not quite sure how to implement it
我是猫鼬的新手(工作2天),我想建立一对多的关系,因为一个人可以来自一个国家,一个国家有很多人。
所以,这就是我所拥有的:
var userSchema = new Schema({
name: String,
username: {
type: String,
required: true,
unique: true
},
password: {
type: String,
required: true
},
country: {
type: Schema.Types.ObjectId,
ref: 'Country'
}
});
var User = mongoose.model('Person', userSchema);
var countrySchema = new Schema({
name: {
type: String,
required: true,
unique: true
},
created_at: Date,
updated_at: Date,
people: [{
type: Number,
ref: 'User'
}]
});
var Country = mongoose.model('Country', countrySchema);
var UK = new Country({
name: 'UK'
});
usa.save(function(err) {
var user = new User({
username: 'James',
password: 'Bond',
country: UK._id
});
user.save(function(err) {
});
});
现在我有两个问题:1)我已经看到ref有时可以是一个ObjectId或仅仅是一个数字-有什么区别? 2)在保存数据时,以我为例,我将国家/地区保存到一个人(通过_id),如何将一个人保存到一个国家? 我应该更新模型的实例吗?
谢谢
更新:
由于此问题已被标记为重复,因此让我改一下这个问题:考虑此链接中的官方示例: http : //mongoosejs.com/docs/populate.html这个想法是一个人有很多故事,一个故事有一位作者(人)。 因此,节省如下:
var aaron = new Person({ _id: 0, name: 'Aaron', age: 100 });
aaron.save(function (err) {
if (err) return handleError(err);
var story1 = new Story({
title: "Once upon a timex.",
_creator: aaron._id // assign the _id from the person
});
story1.save(function (err) {
if (err) return handleError(err);
// thats it!
});
});
这是从官方文档-我的问题是,在这里还是我们如何保存story1
的Author
? Author
是在Story
之前创建的,因此不应该使用story1._id
更新Author
更新2:
我发现,如果仅使用type: Schema.Types.ObjectId
而从不type: Number
,那么我可以做到这一点:
var aaron = new Person({ _id: 0, name: 'Aaron', age: 100 });
var story1 = new Story({
title: "Once upon a timex.",
_creator: aaron._id // assign the _id from the person
});
aaron.stories.push(story1._id);
aaron.save(function (err) {
if (err) return handleError(err);
});
story1.save(function (err) {
if (err) return handleError(err);
// thats it!
});
这实际上在一个虚拟示例中有效...如果请求中的帖子过多而ID可能丢失/重复,是否会出现问题? 这种方法的缺点是什么?
1)我已经看到ref有时可以是一个ObjectId或只是一个数字-有什么区别?
请参考此问题, 为什么他们在猫鼬人口示例中使用ObjectId和Number?
我们在哪里或如何将Story1保存到作者
aaron.save(function (err) {
if (err) return handleError(err);
var story1 = new Story({
title: "Once upon a timex.",
_creator: aaron._id // assign the _id from the person
});
story1.save(function (err) {
if (err) return handleError(err);
// save id of story1 into person here, also you should use `update` operation with `$push` operator.
aaron.stories.push(story1._id);
aaron.save(function(err){
if (err)
handleError(err);
else
console.log('save person successfully...');
})
});
});
结果
> db.stories.find()
{ "_id" : ObjectId("56f72f633cf1e6f00159d5e7"), "title" : "Once upon a timex.", "_creator" : 0, "fans" : [ ], "__v" : 0 }
> db.people.find()
{ "_id" : 0, "name" : "Aaron", "age" : 100, "stories" : [ ObjectId("56f72f633cf1e6f00159d5e7") ], "__v" : 1 }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.