我正在为一个约会应用程序建立一个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: ???
});

推荐答案

你可以用100来描述它

填充是自动替换指定对象的过程

假设您的事件模式定义如下:

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

要显示如何使用填充,请首先创建person对象aaron = new Person({firstname: 'Aaron'})和event对象event1 = new Event({title: 'Hackathon', location: '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);
});

Mongodb相关问答推荐

防止查找简单字段

MongoDB索引使用

MongoDB通过查找具有多个数组的对象进行聚合

我们可以在Mongoose中这样使用Unique:[True,";This to Unique&qot;]吗

如何将空值单独分组?

MongoDB:如何获取多个$indexOfArray值?

当日期和时间在不同键的字符串中时,Mongo 查询过滤今天的数据

在不知道字段名称的情况下如何引用 MongoDB 中的字段?

从MongoDB迁移到PostgreSQL:为PostgreSQL编写聚合管道查询

如何使用指南针连接到 mongodb replicaset (k8s)

MongoDB 到 Snowflake 连续加载

无法让 Mongoose.js 子文档数组填充

使用 homebrew 和 Xcode 8.1.1 安装 Mongodb 失败

无法使用机器 ip 连接到 mongodb

GeoJSON 和 MongoDB:将点存储为 GeoJSON.Point 是否值得?

在 Heroku 上使用 Node 读取、写入和存储 JSON

在 MongoDB 中合并两个集合

$orderby 和 Sort 之间的 MongoDB 区别

MongoDB服务器仍然可以在没有凭据的情况下访问

如何使用户的邮箱在 mongoDB 中唯一?