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

前端 未结 4 619
时光说笑
时光说笑 2020-12-02 19:10

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

so something like

var personSc         


        
4条回答
  •  天命终不由人
    2020-12-02 19:45

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

    You have to define your foreign keys relationships after your schemas definitions and 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) {...})
    

提交回复
热议问题