gpt4 book ai didi

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

转载 作者:IT老高 更新时间:2023-10-28 13:09:53 35 4
gpt4 key购买 nike

我正在为约会应用构建 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: ???
});

最佳答案

您可以使用 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.

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

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({标题:'Hackathon',位置:'foo'}):

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

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

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

关于node.js - 如何在我的 Mongoose 模式中引用另一个模式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29078753/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com