简体   繁体   English

如何在我的 Mongoose 架构中引用另一个架构?

[英]How to reference another schema in my Mongoose schema?

I'm building a Mongoose schema for a dating app.我正在为约会应用构建一个 Mongoose 模式。

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.我希望每个person的文档都包含对他们去过的所有事件的引用,其中events是系统中具有自己模型的另一个模式。 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你可以用人口来描述它

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.我们可以填充单个文档、多个文档、普通对象、多个普通对象或从查询返回的所有对象。

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

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'}) :为了展示如何使用 populate,首先创建一个人对象aaron = new Person({firstname: 'Aaron'})和一个事件对象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);
});

To reference the ObjectId of one table in another table refer below code要在另一个表中引用一个表的 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;

Model is: Model 是:

addedBy: [{ type: mongoose.Schema.Types.ObjectId, required: true, ref: "Users" }] addedBy: [{ type: mongoose.Schema.Types.ObjectId, required: true, ref: "Users" }]

Controller is: Controller 是:

router.post('/university', async (req, res) => { router.post('/university', async (req, res) => {

var data = new University();
data.isDeleted = false;
data.name = req.body.universityName;

 data.addedBy = await User.findById(req.params._id).populate('Users')
     .then((req, res) => {
     }).catch((req, res) => {
         console.log('Mistake');
     });

data.normalizeName = req.body.universityName;
var save = data.save();

if (save) {
    res.redirect('admin/subject-masters');
} else {
    console.log('Please find the mistake ' + err);
}

console.log(req.body.id);

}); });

When I Post output get Undefined .当我发布 output 时得到Undefined How to fetch User collection ID here.如何在此处获取用户集合 ID。

List item项目清单

var personSchema = mongoose.Schema({
    firstname: String,
    lastname: String,
    email: String,
    gender: {
        type: String,
        enum: ["Male", "Female"]
    }
    dob: Date,
    city: String,
    interests: [interestsSchema],
    eventsAttended[{
        type: mongoose.Schema.Types.ObjectId,
        required: true,
        ref: "Place"
    }], 
**//ref:"Places"...you have put the other model name**
 *OR*
    eventsAttended[{
        type: mongoose.Types.ObjectId,
        required: true,
        ref: "Place"
    }],
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM