文章摘自 https://stackoverflow.com/questions/19287142/populate-a-mongoose-model-with-a-field-that-isnt-an-id/39869551
BookSchema = new mongoose.Schema({
...,
title: String,
authorId: Number,
...
},
{
toObject: {virtuals:true},
});
PersonSchema = new mongoose.Schema({id: Number, ...});
BookSchema.virtual('author', {
ref: 'Person',
localField: 'authorId',
foreignField: 'id',
justOne: true
});
var Book = mongoose.model('Book', BookSchema);
var Person = mongoose.model('Person', PersonSchema);
Book.find({...})
.select({.... authorId ....})
.populate('author')
.exec(function(err, books) {...})