如何在我的Mongoose模式中引用另一个模式?

我正在为约会应用程序构build一个Mongoose模式。

我希望每个person文档都包含对所有事件的引用,其中events是系统中具有自己模型的另一个模式。 我怎样才能在模式中描述这个?

 var personSchema = mongoose.Schema({ firstname: String, lastname: String, email: String, gender: {type: String, enum: ["Male", "Female"]} dob: Date, city: String, interests: [interestsSchema], eventsAttended: ??? }); 

你可以使用人口来描述它

人口是使用其他集合中的文档自动replace文档中的指定path的过程。 我们可以填充单个文档,多个文档,普通对象,多个普通对象或从查询返回的所有对象。

假设你的事件模式定义如下:

 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); 

为了显示如何使用填充,首先创build一个person对象, 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') // only works if we pushed refs to person.eventsAttended .exec(function(err, person) { if (err) return handleError(err); console.log(person); });