【问题标题】:Mongoose one-to-many - not quite sure how to implement itMongoose 一对多 - 不太清楚如何实现它
【发布时间】:2016-07-14 06:49:02
【问题描述】:

我对 Mongoose 比较陌生(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 保存到 AuthorAuthor是在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 可能会丢失/重复,是否有任何问题?这种方法有什么缺点?

【问题讨论】:

  • 你为什么想要这个循环引用?如果要选择来自特定国家/地区的所有用户,只需在 country = yourCountry 的用户中搜索即可。
  • 那么在多对多关系中怎么样,需要有这个循环引用..或者?
  • 然后,每个人都可以有一个他来自国家的列表。
  • 你为什么想要这个循环引用? - 我从他们的规范中提供了一个官方示例。虽然我了解模型,但我不确定如何相应地保存数据

标签: node.js mongodb mongoose


【解决方案1】:

1) 我发现 ref 有时可以是 ObjectId 或只是一个数字 - 有什么区别?

请参考这个问题Why do they use an ObjectId and a Number in the Mongoose Population example?

我们在哪里或如何将故事 1 保存给作者

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 }

【讨论】:

  • 如果故事被删除怎么办?
  • 谢谢,这是我一直在问的问题,但是,我想出了一个更简单、更简洁的方法——请参阅我原帖中的“更新 2”。再次感谢!
  • @uglycode,你的代码的一个问题是如果aaron保存失败,但story1保存成功怎么办?
  • @Cristy,在删除一个故事文档之前,从个人文档的字段stories$pull 中删除故事的_id。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-15
  • 1970-01-01
  • 2015-06-10
  • 2021-11-11
  • 1970-01-01
相关资源
最近更新 更多