How to reference another schema in my Mongoose schema?

I am creating a Mongoose schema for a dating application.

I want each person document to contain a link to all the events to which they were, where events is a different scheme with its own models in the system. How can I describe this in a diagram?

 var personSchema = mongoose.Schema({ firstname: String, lastname: String, email: String, gender: {type: String, enum: ["Male", "Female"]} dob: Date, city: String, interests: [interestsSchema], eventsAttended: ??? }); 
+6
source share
1 answer

You can describe it using Population

Population is the process of automatically replacing a specified path in a document with documents from other collections (s). We can fill out one document, several documents, a simple object, several simple objects, or all objects returned from a request.

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 padding is used, first create a person object, aaron = new Person({firstname: 'Aaron'}) and an event object, event1 = new Event({title: 'Hackathon', location: 'foo'}) :

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

Then, when you make your request, you can fill out the following links:

 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); }); 
+14
source

Source: https://habr.com/ru/post/983871/


All Articles