Create mongoose reference of models in differents files - reference

I need to create references to 2 models which are in different files. My models are:
Profesor
Curso
I want Curso to have a reference to a Profesor. My problem is that when the models Curso is being created, the model Profesor does not exist yet.
MissingSchemaError Schema hasn't been registered for model Profesor
If the reference is to the model Alumno there isnĀ“t problem because Alumno is created before Curso right?

Just create all your schemas first and then register your models. And do all of this when you bootstrap your app, before anything else. Then you won't have such issues. An example from the docs, where two schema reference each other:
http://mongoosejs.com/docs/populate.html
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
title : String,
fans : [{ type: Number, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);

Related

What data structure should i use in mongoDB

I am making a small project in MEAN stack but I can not figure out what data structure to use.
So, in this case, I don't have any reference in the store I just fetch store when a person asks for his or her stores.
var personSchema = Schema({
_id : Number,
name : String,
stores: [{ type: Schema.Types.ObjectId, ref: 'Store' }]
});
var storeSchema = Schema({
_id : Number,
title : String
});
AND:
In this case, I give the store a reference of the person so when a person asks for his or her stores I fetch all the store which has a reference to the person.
var personSchema = Schema({
_id : Number,
name : String
});
var storeSchema = Schema({
_id : Number,
owner : { type: Schema.Types.ObjectId, ref: 'Person' },
title : String
});
Which one is better approach?
First one is better to use as it helps in clean code and queries.

Car reservation with mongoose and references

I am new to mongoDB and i am building a reservation system with cars. What i am trying to do is to get the cars which are not reserved. The user give the dates he wants to rent the car and i must show him the available ones.
Can i do this with one query? I've done this with MySql but i am confused with mongoose..
I have this Car model
const mongoose = require('mongoose');
const carSchema = mongoose.Schema({
brand: String,
model: String,
power: String,
seats: Number,
imgUrl: String,
});
module.exports = mongoose.model('Car', carSchema);
And this reservation model
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const reservationSchema = Schema({
car_id: { type: Schema.Types.ObjectId, ref: 'Car' },
from: Date,
until: Date,
});
module.exports = mongoose.model('Reservation', reservationSchema);
Reservation will have many cars, so your reservationSchema should be:
const reservationSchema = Schema({
car:[ { type: Schema.Types.ObjectId, ref: 'cars' }],
from: Date,
until: Date,
});
Consider another model: availableCarSchema. All cars are here. When a car is resrved, it is removed from this document, and when the reservation ends, the car is added back to this document.
So to find available cars, you'd query availableCars like this:
AvailableCars.find({brand:'preferred brand',model:'preferred model',other propertis})

run time collections in express.js

I am creating a web app, where user can create questions. Every time user creates a question a collection should be created, where all the answers to that question should be saved as documents in that collection.
You can use mongodb ORM - mongoose for making your data models like that
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var questionSchema = Schema({
title : String,
text : String,
user : { type: Schema.Types.ObjectId, ref: 'User' },
answers : [{ type: Schema.Types.ObjectId, ref: 'Answer' }]
});
var answerSchema = Schema({
user : { type: Schema.Types.ObjectId, ref: 'User' },
text : String,
});
var Question = mongoose.model('Question', questionSchema);
var Answer = mongoose.model('Answer', answerSchema);
So you will store array of answer ids inside question and can populate data:
Question.findOne().populate('answers').exec(function(err, doc){
console.log(doc.answers) // here populated answers models
})
Also you need describe User model and extend with additional data Question and Answer

mongoose - possible circular dependency?

I have the following mongoose models in my express app:
//dog.js
var mongoose = require("mongoose");
var dogSchema = (exports.dogSchema = mongoose.Schema({
name: { type: String, required: true },
}));
Then I import dog.js to my user.js
//user.js
var mongoose = require("mongoose");
var dog = require("./dog");
var userSchema = mongoose.Schema({
user: { type: String, required: true },
pass: { type: String, required: true },
dogs: [dog.dogSchema],
});
Now, from my routes I am creating a new user like this:
var user = require("../models/user");
var dog = require("../models/dog");
dog = new dog.Dog(dogData);
user = new user.User(data); //this will of course contain also dogData
user.save(next);
Is this the correct way to do this kind of operation? I have the feeling that I might be generating a circular dependency somehow, and anyway it does not look right to me. Any ideas on how to create sub-documents where the schema is from another model file?
You can create simultaneous references in two directions without creating circular problems. Create a reference from one document to the other using ref. From the docs:
http://mongoosejs.com/docs/populate.html
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
title : String,
fans : [{ type: Number, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
Then you can then choose to load the sub document using populate
Story.find({ --your criteria-- })
.populate('_creator')
.exec(function (err, story) {../});
You can then store the 2 schemas in separate .js files and require them both

Why do they use an ObjectId and a Number in the Mongoose Population example?

In this example, they create personSchema using ObjectId to reference the Story and this I understand. But then in storySchema why don't they do the same to reference the person?
Or the inverse: why using ObjectId instead of Number in Person?
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var personSchema = Schema({
_id : Number,
name : String,
age : Number,
stories : [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});
var storySchema = Schema({
_creator : { type: Number, ref: 'Person' },
title : String,
fans : [{ type: Number, ref: 'Person' }]
});
var Story = mongoose.model('Story', storySchema);
var Person = mongoose.model('Person', personSchema);
Type of reference has to be the same as the referenced schema's _id property.
In case of personSchema it's a Number.
storySchema on the other hand, has the _id field assigned automatically by mongoose - it's not specified in parameters for the schema constructor.
Mongoose assigns each of your schemas an _id field by default if one is not passed into the Schema constructor. The type assiged is an ObjectId to coincide with MongoDBs default behavior

Resources