使用非id的字段填充mongoose模型

ang*_*ord 21 mongoose mongodb node.js

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

所以像

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

Fro*_*y Z 68

Mongoose 4.5开始支持此功能,称为虚拟填充.

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

// 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) {...})
Run Code Online (Sandbox Code Playgroud)

  • 这不应该是现在接受的答案吗? (7认同)

lee*_*sei -7

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

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

您可以混合搭配find()

  • 仅在阅读文档后才来到 SO,如果我理解它,我就不会在这里搜索答案。 (8认同)
  • 我无法从文档中理解。你能给出一个示例查询吗? (4认同)