【问题标题】:How to reference another schema in my Mongoose schema?如何在我的 Mongoose 模式中引用另一个模式?
【发布时间】:2015-05-18 16:20:48
【问题描述】:

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

【问题讨论】:

  • 我相信是这样的:eventsAttended: [{ type: app.mongoose.Schema.ObjectId, ref: 'Event'}]

标签: node.js mongodb mongoose


【解决方案1】:

你可以用Population来描述它

填充是自动替换指定的过程 文档中的路径以及来自其他集合的文档。我们 可以填充单个文档、多个文档、普通对象、 多个普通对象,或从查询返回的所有对象。

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

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

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

【讨论】:

  • 我可以问你一个问题吗?如果我还想在event 架构中拥有一个attendees 列表怎么办?这会导致循环问题吗?
  • 您可以在两个方向上同时创建参考,而没有任何可能的循环依赖。 Mongoose 文档中的Story and Person schemas 示例很好地说明了这一点。
  • EventAttended 的 TypeScript 会是什么?
  • @chridam 感谢您的回答!
【解决方案2】:

要在另一个表中引用一个表的 ObjectId,请参考下面的代码

const mongoose = require('mongoose'),
Schema=mongoose.Schema;

const otpSchema = new mongoose.Schema({
    otpNumber:{
        type: String,
        required: true,
        minlength: 6,
        maxlength: 6
    },
    user:{
        type: Schema.Types.ObjectId,
        ref: 'User'
    }
});

const Otp = mongoose.model('Otp',otpSchema);

// Joi Schema For Otp
function validateOtp(otp) {
    const schema = Joi.object({
        otpNumber: Joi.string().max(6).required(),
        userId: Joi.objectId(),   // to validate objectId we used 'joi-objectid' npm package
        motive: Joi.string().required(),
        isUsed: Joi.boolean().required(),
        expiresAt: Joi.Date().required()
    });
    // async validate function for otp
    return schema.validateAsync(otp);
}

exports.Otp = Otp;
exports.validateOtp = validateOtp;

【讨论】:

    猜你喜欢
    • 2013-08-02
    • 2022-01-21
    • 1970-01-01
    • 1970-01-01
    • 2015-09-14
    • 2016-03-18
    • 2017-06-09
    • 2016-05-29
    • 1970-01-01
    相关资源
    最近更新 更多