如何在我的Mongoose模式中引用另一个模式? [英] How to reference another schema in my Mongoose schema?

查看:35
本文介绍了如何在我的Mongoose模式中引用另一个模式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为约会应用构建Mongoose模式.

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

我希望每个person文档都包含对其经历过的所有事件的引用,其中events是系统中具有其自身模型的另一个架构.如何在架构中对此进行描述?

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

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

推荐答案

您可以使用 人口

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

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

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'}):

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

这篇关于如何在我的Mongoose模式中引用另一个模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆