ten jest wspierany od Mongoose 4,5 i nazywa virtuals population.
Trzeba zdefiniować kluczy obcych relacje po swoim schematów definicje i przed tworzenia modeli, podobnie jak to:
// Schema definitions
BookSchema = new mongoose.Schema({
...,
title: String,
author_id: 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: 'author_id',
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({.... author_id ....})
// use the 'virtual population' name
.populate('author')
.exec(function(err, books) {...})
przodu do 2017, a odpowiedź Frosty powinny być zaakceptowane odpowiedź. – user553086