本文介绍了如何在我的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

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

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模式中引用另一个模式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 23:08
查看更多