node.js 使用不是 id 的字段填充猫鼬模型

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19287142/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:55:56  来源:igfitidea点击:

Populate a mongoose model with a field that isn't an id

node.jsmongodbmongoose

提问by angulord

Is it possible to populate a mongoose model with a field of a reference model that isn't the _id ... e.g. a username.

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

so something like

所以像

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

采纳答案by leesei

You may use the populate()API. The API is more flexible, you don't have to specify refand fieldin the Schema.

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

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

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

You can mix and match with find().

您可以与find().

回答by Frosty Z

This is supported since Mongoose 4.5, and is called virtuals population.

Mongoose 4.5起支持此功能,称为虚拟人口

You have to define your foreign keys relationshipsafter your schemas definitionsand before creating models, like this:

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

// 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) {...})

回答by Leo Gao

It seems they enforce to use _id, and maybe we can customize it in the future.

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

Here is the issue on Github https://github.com/LearnBoost/mongoose/issues/2562

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

回答by Lotus

This is an example of using the $lookup aggregate to populate a model called Invite with the respective User based on the corresponding emailfield:

这是使用 $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);
    }
  );

It's probably quite similar to what you're trying to do.

它可能与您尝试做的非常相似。