【问题标题】:Mongoose reference other collection via ObjectIDMongoose 通过 ObjectID 引用其他集合
【发布时间】:2018-06-11 22:09:05
【问题描述】:

我已经阅读了this guide 以构建数据库。我理解这一点,但我想在我自己的 RESTful API 中实现这个想法,但似乎我违背了我迄今为止提出的意图。

在链接的 MongoDB 文档中,它谈到了通过简单地引用 ObjectID 来节省空间,我试图这样做并遵循 Mongoose 人口文档here

但在实施此操作后,我将完整的问题数据添加到我的用户中,如下所示:

而不是 MongoDB 中的建议方式:

{
    name : 'left-handed smoke shifter',
    manufacturer : 'Acme Corp',
    catalog_number: 1234,
    parts : [     // array of references to Part documents
        ObjectID('AAAA'),    // reference to the #4 grommet above
        ObjectID('F17C'),    // reference to a different Part
        ObjectID('D2AA'),
        // etc
    ]

由于问题的潜在规模,我不想将问题嵌入到用户中,而是引用他们的 ID,然后使用它通过他们的特定用户获取所有问题问题数组。我确实设法在猫鼬中保存了一个数组,但发现我找不到如何从 ID 中提取完整的文档并将它们全部显示出来,所以如果可能的话,我们将不胜感激。

【问题讨论】:

    标签: node.js mongodb mongoose mongoose-schema mongoose-populate


    【解决方案1】:

    使用mongoose-autopopulate插件

    例子

       var bandSchema = new Schema({
          name: String,
          lead: { type: ObjectId, ref: 'people', autopopulate: true }
        });
        bandSchema.plugin(autopopulate);
    
        var Band = mongoose.model('band3', bandSchema, 'bands');
        Band.findOne({ name: "Guns N' Roses" }, function(error, doc) {
          assert.ifError(error);
          assert.equal('Axl Rose', doc.lead.name);
          assert.equal('William Bruce Rose, Jr.', doc.lead.birthName);
          done();
        });
    

    或者你可以试试这个

    Modelname.find({})
                .populate('fieldname')           
                .exec(function(error, posts) {
                    console.log(JSON.stringify(posts, null, "\t"))
                })
    

    【讨论】:

    • 我现在只想坚持使用猫鼬,这让我很困惑,我不确定它是否是我之后的解决方案:s
    • 这很简单,一旦你尝试了,它会在未来帮助你
    猜你喜欢
    • 2017-03-16
    • 2017-08-11
    • 1970-01-01
    • 2013-09-27
    • 2013-02-06
    • 2013-08-05
    • 2017-01-22
    • 2021-07-18
    • 2014-10-28
    相关资源
    最近更新 更多