【问题标题】:Populate a mongoose model with a field that isn't an id使用不是 id 的字段填充 mongoose 模型
【发布时间】:2013-10-17 16:53:52
【问题描述】:

是否可以使用不是 _id 的参考模型字段填充猫鼬模型...例如用户名。

类似

var personSchema = Schema({
  _id     : Number,
  name    : String,
  age     : Number,
  stories : { type: String, field: "username", ref: 'Story' }
});

【问题讨论】:

  • 快进到 2017 年,Frosty 的答案应该是公认的答案。

标签: node.js mongodb mongoose


【解决方案1】:

Mongoose 4.5 开始支持此功能,称为 virtuals population

您必须在模式定义之后和创建模型之前定义您的外键关系,如下所示:

// Schema definitions

BookSchema = new mongoose.Schema({
        ...,
        title: String,
        authorId: Number,
        ...
    },
    // schema options: Don't forget this option
    // if you declare foreign keys for this schema afterwards.
    {
        toObject: {virtuals:true},
        // use if your results might be retrieved as JSON
        // see http://stackoverflow.com/q/13133911/488666
        //toJSON: {virtuals:true} 
    });

PersonSchema = new mongoose.Schema({id: Number, ...});


// Foreign keys definitions

BookSchema.virtual('author', {
  ref: 'Person',
  localField: 'authorId',
  foreignField: 'id',
  justOne: true // for many-to-1 relationships
});


// Models creation

var Book = mongoose.model('Book', BookSchema);
var Person = mongoose.model('Person', PersonSchema);


// Querying

Book.find({...})
    // if you use select() be sure to include the foreign key field !
    .select({.... authorId ....}) 
    // use the 'virtual population' name
    .populate('author')
    .exec(function(err, books) {...})

【讨论】:

  • 我只是假设它是答案
【解决方案2】:

他们似乎强制使用_id,也许我们将来可以自定义它。

这是 Github 上的问题https://github.com/LearnBoost/mongoose/issues/2562

【讨论】:

【解决方案3】:

这是一个使用 $lookup 聚合根据相应的 email 字段使用相应用户填充名为 Invite 的模型的示例:

  Invite.aggregate(
      { $match: {interview: req.params.interview}},
      { $lookup: {from: 'users', localField: 'email', foreignField: 'email', as: 'user'} }
    ).exec( function (err, invites) {
      if (err) {
        next(err);
      }

      res.json(invites);
    }
  );

这可能与您尝试执行的操作非常相似。

【讨论】:

    【解决方案4】:

    您可以使用populate() API。 API更加灵活,不必在Schema中指定reffield

    http://mongoosejs.com/docs/api.html#document_Document-populate http://mongoosejs.com/docs/api.html#model_Model.populate

    你可以和find()混搭。

    【讨论】:

    • 我无法从文档中理解。你能举个例子吗?
    • 只有在阅读了文档后才进入 SO,如果我理解了,我不会在这里搜索答案。
    • 您仍然需要通过添加参考来配置要使用的 Schema 以进行填充。
    猜你喜欢
    • 2019-09-17
    • 2015-06-09
    • 1970-01-01
    • 2012-01-22
    • 2021-10-04
    • 2017-05-21
    • 2018-10-22
    • 1970-01-01
    • 2017-10-24
    相关资源
    最近更新 更多