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

Cod*_*ein 16 mongoose mongodb node.js

我正在为约会应用程序构建一个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: ???
});
Run Code Online (Sandbox Code Playgroud)

chr*_*dam 30

您可以使用人口来描述它

填充是使用来自其他集合的文档自动替换文档中的指定路径的过程.我们可以填充单个文档,多个文档,普通对象,多个普通对象或从查询返回的所有对象.

假设您的事件架构定义如下:

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);
Run Code Online (Sandbox Code Playgroud)

要显示如何使用populate,首先要创建一个person对象aaron = new Person({firstname: 'Aaron'})和一个事件对象event1 = new Event({title: 'Hackathon', location: 'foo'}):

aaron.eventsAttended.push(event1);
aaron.save(callback); 
Run Code Online (Sandbox Code Playgroud)

然后,当您进行查询时,可以填充这样的引用:

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);
});
Run Code Online (Sandbox Code Playgroud)

  • eventsAttished 的 TypeScript 是什么? (3认同)
  • 我可以问你一个问题吗?如果我还想在“事件”模式中拥有“与会者”列表怎么办?这会导致循环问题吗? (2认同)
  • 您可以在两个方向上创建同时引用,而没有任何可能的循环依赖关系 Mongoose docs中[**Story and Person schemas**](http://mongoosejs.com/docs/populate.html)的例子很好地解释了这一点. (2认同)