Mongoose通过ObjectID引用其他集合

问题描述 投票:0回答:1

我读过this guide来建立数据库。我理解它,但我想在我自己的RESTful API中实现这个想法,但似乎我反对我迄今为止所提出的目标。

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

但在实现此功能后,我将向用户添加完整的问题数据,如下所示:

image of mongodb document

而不是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,然后使用它来通过他们的问题数组获取所有特定用户的问题。我确实设法只在mongoose中保存一个数组,但发现我找不到如何从ID中提取完整的文档并将它们全部显示出来,所以如果可能的话,我会很感激。

node.js mongodb mongoose mongoose-schema mongoose-populate
1个回答
0
投票

使用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"))
            })
© www.soinside.com 2019 - 2024. All rights reserved.