简体   繁体   English

一对多猫鼬-不太清楚如何实施

[英]Mongoose one-to-many - not quite sure how to implement it

I'm relatively new to Mongoose (2 days at it) and I want to make a one-to-many relationship, as in one person can come from one country, one country has many people. 我是猫鼬的新手(工作2天),我想建立一对多的关系,因为一个人可以来自一个国家,一个国家有很多人。

So, this is what I've got: 所以,这就是我所拥有的:

    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) {

    });

});

Now I have two questions: 1) I've seen that ref can sometimes be an ObjectId or just a number - what's the differences? 现在我有两个问题:1)我已经看到ref有时可以是一个ObjectId或仅仅是一个数字-有什么区别? 2) when saving the data, in my case, I saved country to a person (by _id), how do I save a person to a country? 2)在保存数据时,以我为例,我将国家/地区保存到一个人(通过_id),如何将一个人保存到一个国家? Should I update the instance of the model? 我应该更新模型的实例吗?

Thanks 谢谢

UPDATE: 更新:

since this question has been marked as a duplicate, let me rephrase the question: consider the official example in this link: http://mongoosejs.com/docs/populate.html The idea is that one person has many stories, and one story has one author (person). 由于此问题已被标记为重复,因此让我改一下这个问题:考虑此链接中的官方示例: http : //mongoosejs.com/docs/populate.html这个想法是一个人有很多故事,一个故事有一位作者(人)。 So, the saving would be as follows: 因此,节省如下:

    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!
  });
}); 

That's from the official documentation - my question is, where or how do we save story1 to the Author ? 这是从官方文档-我的问题是,在这里还是我们如何保存story1Author Author is created before the Story , so, shouldn't the Author be updated with story1._id ??? Author是在Story之前创建的,因此不应该使用story1._id更新Author

UPDATE 2: 更新2:

I figured out that if I use only type: Schema.Types.ObjectId and never type: Number , that I can do just this: 我发现,如果仅使用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!
}); 

This actually works in a dummy example... are there any problems if there were too many posts in a request that IDs could have get lost/duplicated? 这实际上在一个虚拟示例中有效...如果请求中的帖子过多而ID可能丢失/重复,是否会出现问题? What is the shortcoming of this approach? 这种方法的缺点是什么?

1) I've seen that ref can sometimes be an ObjectId or just a number - what's the differences? 1)我已经看到ref有时可以是一个ObjectId或只是一个数字-有什么区别?

Please refer to this question Why do they use an ObjectId and a Number in the Mongoose Population example? 请参考此问题, 为什么他们在猫鼬人口示例中使用ObjectId和Number?

where or how do we save story1 to the Author 我们在哪里或如何将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...');
    })
  });
});

The results 结果

> 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM