我對貓鼬比較新(在它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)我已經看到了裁判有時可以是一個或的ObjectId只是一個數字 - 有什麼區別? 2)在保存數據時,就我而言,我將國家保存到一個人身邊(通過_id),我如何將一個人救到一個國家?我應該更新模型的實例嗎?
感謝
UPDATE:
,因爲這個問題已經被標記爲重複,讓我改一下這個問題:考慮在這個環節正式例如: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
之前創建,所以,不應該Author
更新爲story1._id
???
更新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可能會丟失/重複,那麼是否存在任何問題?這種方法有什麼缺點?
你爲什麼要有這個循環參考?如果您想選擇特定國家/地區的所有用戶,只需在國家= yourCountry的用戶中進行搜索。 – Cristy
在多對多的關係中如何,需要有這個循環引用..或者? – uglycode
可能的重複[在mongoDB中是否可以使用循環對象引用?](http://stackoverflow.com/questions/21413864/are-circular-object-references-possible-in-mongodb) – Cristy