如何在我的Mongoose模式中引用另一个模式?

时间:2015-03-16 14:03:16

标签: node.js mongodb mongoose

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

2 个答案:

答案 0 :(得分:24)

您可以使用 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);
});

答案 1 :(得分:0)

要在另一个表中引用一个表的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;