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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29078753/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 18:32:06  来源:igfitidea点击:

How to reference another schema in my Mongoose schema?

node.jsmongodbmongoose

提问by CodyBugstein

I'm building a Mongoose schema for a dating app.

我正在为约会应用程序构建 Mongoose 模式。

I want each persondocument to contain a reference to all the events they've been to, where eventsis another schema with its own models in the system. How can I describe this in the schema?

我希望每个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: ???
});

回答by chridam

You can describe it by using Population

你可以用人口来描述它

Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s). We may populate a single document, multiple documents, plain object, multiple plain objects, or all objects returned from a query.

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

Suppose your Event Schema is defined as follows:

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

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

To show how populate is used, first create a person object, aaron = new Person({firstname: 'Aaron'})and an event object, event1 = new Event({title: 'Hackathon', location: 'foo'}):

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

aaron.eventsAttended.push(event1);
aaron.save(callback); 

Then, when you make your query, you can populate references like this:

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

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