One to Many relationship in Express Models using mongoDB - node.js

This is doctors.js model:
var mongoose = require('mongoose'), Schema = mongoose.Schema;
var Patient = require('./patient.js');
var doctorSchema = mongoose.Schema({
firstName: String,
lastName: String,
qualifications: String,
photo: Buffer,
_patients: [{ type: Schema.Types.ObjectId, ref: 'Patient' }]
});
var Doctor = mongoose.model('Doctor', doctorSchema);
module.exports = Doctor;
This is patients.js model:
var mongoose = require('mongoose');
var Doctor = require('./doctor.js');
var patientSchema = mongoose.Schema({
firstName: String,
lastName: String,
dob: String,
gender: String,
primaryDiagnosis: String,
duration: String,
_doctorIncharge: {type: Number, ref: 'Doctor'},
hospitalNumber: String,
photo: Buffer
});
var Patient = mongoose.model('Patient', patientSchema);
module.exports = Patient;
Is this the way to make a one to many relationship work?

Related

MongoDB: How to get data by join

I am having following two schemas in mongodb
var userSchema = new Schema({
first_name: String,
last_name: String,
email: String
});
var messageSchema = new Schema({
sender: {type: Schema.Types.ObjectId, ref: 'users' },
receiver: {type: Schema.Types.ObjectId, ref: 'users' },
message: String,
sentOn: Date,
});
var Users = mongoose.model('users', userSchema);
var Messages = mongoose.model('messages', messageSchema);
How can I query to get the all users from 'users' collection and their last message (single) from 'messages' collection?

Mongoose Nested Populate Not Working

So I am currently extremely confused when it comes to mongoose populating.
My data structure is as follows: User has an array of Clients, a Client has an array of loans. I am using User.find and populating the client, no problem. But then how do I populate the loans that is inside of the client? I have tried this:
Basically, the goal is to pass in an array of Clients, each client will contain a loan. But for now, I want that loan object to be empty. The Client is being populated correctly, however, the Loan reference is being passed as undefined.
app.get("/loans", IsLoggedIn, function(req, res) {
User.findById(req.user._id).populate({path: "clients", populate: { path: "loans", model: "loan"}}).exec(function(err, user){
if(err){
console.log(err);
} else{
var amountRepaid = calcRepaid(user.clients.loans);
console.log(user.clients.loans);
res.render("index", {clients: user.clients, amountRepaid: amountRepaid});
}
});
However it doesn't seem to work, my models are listed below and any help is appreciated!
models:
Client:
var mongoose = require("mongoose");
var clientSchema = mongoose.Schema({
loans: [{
type: mongoose.Schema.Types.ObjectId,
ref: "loan"
}],
emailAdderess: String,
firstname: String,
lastname: String,
contactNumber: String ,
dateCreated: {type: Date, default: Date.now},
gender: String,
})
module.exports = mongoose.model("Client", clientSchema);
User:
const mongoose = require("mongoose");
const passportLocalMongoose = require("passport-local-mongoose");
var UserSchema = mongoose.Schema({
username: String,
password: String,
firstname: String,
lastname: String,
clients: [{
type: mongoose.Schema.Types.ObjectId,
ref: "Client"
}]
});
UserSchema.plugin(passportLocalMongoose);
module.exports = mongoose.model("User", UserSchema);
Loan:
var mongoose = require("mongoose");
var LoanSchema = mongoose.Schema({
firstName: String,
lastName: String,
email: String,
contactNumber: Number,
amountBorrowed: Number,
length: String,
address: String,
dateDue: Date,
gender: String,
date: { type: Date, default: Date.now },
amountRepaid: { type: Number, default: 0},
loanRepaid: {type: Boolean, default: false}
})
module.exports = mongoose.model("loan", LoanSchema);
Try this:
.populate({
path: 'clients',
populate: {
path: 'clients.loans'
}
})

Register Schema - Mongo Relationship

im new working with mongoDB and node.js im trying to creat a relation between two models applications and contactsapp
applicationsModel
'use strict'
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const contactapp = mongoose.model('ContactApp');
const ApplicationsSchema = Schema({
application_code: String,
name: String,
comments: String,
version: String,
developer: String,
url: String,
active: Boolean,
press_package: String,
pad_file: String,
image: String,
category: [String],
contacts: [{ type: Schema.ObjectId, ref: "ContactApp" }]
});
module.exports = mongoose.model('Applications', ApplicationsSchema);
contactsappModel
'use strict'
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ContactappSchema = Schema({
fullname: String,
avatar: String,
company: String,
jobTitle: String,
email: String,
phone: String,
sex: String,
country: String,
channel: String,
website_url: String,
linkedin_url: String,
xing_url: String,
notes: String,
active: Boolean
});
module.exports = mongoose.model('ContactApp',ContactappSchema);
but when the console give me the error Schema hasn't been registered for model "ContactApp".
Your app probably loads applicationsModel.js before contactsappModel.js, so the ContactApp model hasn't been registered yet when this line is executed:
const contactapp = mongoose.model('ContactApp');
Since you're not using the contactapp variable anyway, try removing that line entirely.

ReferenceError: <model> is not defined

I have several schemas defined. Here's one that works fine:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var NewsSchema = new Schema({
name: String,
route: String,
remoteURL: String,
articles: [{title: String, link: String, Image: String, contentSnippet: String}],
retrieved: Date,
dormant: { type: Boolean, default: false}
});
module.exports = mongoose.model('News', NewsSchema);
Here's a second one that's nearly identical:
var mongoose = require('mongoose'),
Schema = mongoose.Schema
// NewsSchema = new Schema({ name: String });
var ArticlesSchema = new Schema({
title: String,
link: String,
pubDate: Date,
image: String,
contentSnippet: String,
sourceName: String
// sourceId: [ {type: Schema.Types.ObjectId, ref: NewsSchema}]
});
module.exports = mongoose.model('Articles', ArticlesSchema);
I've loaded both of the modules at the top of my program, along with a bunch of other stuff like this:
players = require('./app/models/players'),
articles = require('./app/models/articles'),
If I create an instance of the first one with something like:
var player = new Players();
But if I try to create an instance of the second one with:
var item = new Articles();
I receive the error in the subject. In tracing the code I can see that the modules are in scope, so I don't believe it's something stupid like redefining a variable or something like that.
Any ideas?
There is a missing quote mark, so
Instead of
sourceId: [ {type: Schema.Types.ObjectId, ref: NewsSchema}]
use
sourceId: [ {type: Schema.Types.ObjectId, ref: 'NewsSchema'}]
would solve your problem.

How to reference another schema in my Mongoose schema?

I'm building a Mongoose schema for a dating app.
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. 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 do so 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'}):
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
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;
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"
}],
});

Resources