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

查看:23
本文介绍了如何在我的 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是自动替换指定的过程包含来自其他集合的文档的文档中的路径.我们可以填充单个文档、多个文档、普通对象、多个普通对象,或从查询返回的所有对象.

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

要展示如何使用 populate,首先创建一个 person 对象,aaron = new Person({firstname: 'Aaron'}) 和一个事件对象,event1 = new Event({标题:'黑客马拉松',地点:'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天全站免登陆