你可以使用
Population来实现。Population是自动将文档中指定路径替换为另一个集合中的文档的过程。我们可以填充单个文档、多个文档、纯对象、多个纯对象或查询返回的所有对象。假设你的事件模式定义如下:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var eventSchema = Schema({
title : String,
location : String,
startDate : Date,
endDate : Date
});
var personSchema = Schema({
firstname: String,
lastname: String,
email: String,
gender: {type: String, enum: ["Male", "Female"]}
dob: Date,
city: String,
interests: [interestsSchema],
eventsAttended: [{ type: Schema.Types.ObjectId, ref: 'Event' }]
});
var Event = mongoose.model('Event', eventSchema);
var Person = mongoose.model('Person', personSchema);
为了展示populate的使用方法,首先创建一个人对象,
aaron = new Person({firstname: 'Aaron'})
和一个事件对象,
event1 = new Event({title: 'Hackathon', location: 'foo'}):
aaron.eventsAttended.push(event1);
aaron.save(callback);
然后,当您进行查询时,可以像这样填充引用:
Person
.findOne({ firstname: 'Aaron' })
.populate('eventsAttended')
.exec(function(err, person) {
if (err) return handleError(err);
console.log(person);
});
eventsAttended: [{ type: app.mongoose.Schema.ObjectId, ref: 'Event'}]
,其中包括一个类型为app.mongoose.Schema.ObjectId
的eventsAttended
属性和引用了'Event'
的对象。 - Sergio Tulentsev