How to verify if email exists in two seperate documents of mongoose? - javascript

I have two models, patients and doctors. When the user signs in, be it the doctor or patient, there is only one route which runs the login function of the backend. But what I fail to understand is how to query such that it searches in both collections of patients and doctors by using single query.
This is the doctor model:
const doctorSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
practitionerLicense: {
type: String,
required: true
}
});
module.exports = Doctor = mongoose.model("doctors", doctorSchema);
And the patient model:
const patientSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = Patient = mongoose.model("patient", patientSchema);
Now I want something like the following pseudo code where users could be like a base class or something.
Users.findOne({email}).then(...)
I went through many other similar questions but saw methods like populate which I believe would not suit my case. Any suggestions?

Your patient and doctor schemas are almost same except the practitionerLicense field.
So instead of two different schemas, I would create a common user schema with an additional role field like this:
const userSchema = new Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
email: {
type: String,
required: true
},
password: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
},
practitionerLicense: {
type: String,
required: false
},
role: {
type: String,
enum: ["patient", "doctor"],
required: true
}
});
module.exports = User = mongoose.model("users", userSchema);
Note that I also set practitionerLicense's required option to false.
This way you can use a common user login form and route.
Your register route and register form in React can also be common, if you could verify if a user enters a practitioner license, and you can validate it using an API if there is such an API.
If that is not possible, your register routes and register components must be different for patient and doctor. When a user registers in patient register form, you can set role to patient. And when a user registers in doctor register form, you can set role to doctor.

Related

Mongoose Schema cannot be identified by code

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
//broken schema
var coursesSchema = new Schema({
college: {
type: String,
required: true
},
units: {
type: Number,
required: true
},
course_code: {
type: String,
required: true
},
course_name: {
type: String,
required: true
},
class_number: {
type: String,
required: true
},
section: {
type: String,
required: true
},
class_day: {
type: String,
required: true
},
time_start: {
type: String,
required: true
},
time_end: {
type: String,
required: true
},
faculty: {
type: String,
required: true
}
});
module.exports = mongoose.model('Courses', coursesSchema);
//working schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var loaSchema = new Schema({
process_name: {
type: String,
required: true
},
process_details: {
type: String,
required: true
},
process_deadline: {
type: String,
required: true
},
});
module.exports = mongoose.model('LOA', loaSchema);
I have this schema which I export into index.js file. This schema works in other parts of the code except in index.js. When I query Courses schema, it returns model.find() is not a function. When I try creating a new Courses object it says Constructor is not a schema. I have other schemas that work fine inside index.js and I get to query them, but this schema is an exception.
Does anyone know the reason behind this?
index.js is the special file and actually it's root of your module, it's better separate the schema from that to prevent from bugs

can a mongoose schema field reference more than one other models

I have a mongoose schema field called "bookmarks" and I would like it to reference more than one model. for example, if I have 2 other models named "post" and "complain". I would like the user to be able to bookmark both of them.
const userSchema = new mongoose.Schema({
fullname: {
type: String,
required: true,
trim: true,
lowercase: true
},
username: {
type: String,
unique: true,
required: true,
trim: true,
lowercase: true
},
email: {
type: String,
unique: true,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Email is invalid')
}
}
},
bookmarks: [{
type: mongoose.Schema.Types.ObjectId,
required: false,
ref: 'Post'
}],
})
below is a post model, where users can post things in general
const postSchema = new mongoose.Schema({
body: {
type: String,
required: true,
trim: true,
lowercase: true
}
})
below is a complain model, where users can post a complain
const complainSchema = new mongoose.Schema({
body: {
type: String,
required: true,
trim: true,
lowercase: true
}
})
How can I get the bookmarks field in the user model to be able to get the object id of both the complain model and the post model?
You can nest those two models in userSchema itself just like you are doing with bookmark schema .
You can also refer to this link , i hope it will resolve your query.
Link - : What is the proper pattern for nested schemas in Mongoose/MongoDB?
Here is the correct way to achieve this.
First remove bookmarks
Add this
ref: {
kind: String, // <-- Model Name post,complain
item: {
type: mongoose.Schema.Types.ObjectId,
refPath: 'ref.kind',
fields: String,
},
},
When you want to fetch the records,you can use populate
model.User.find({})
.populate({ path: 'ref.item' })
.then(data=>{console.log(data)})
.catch(err => {console.log(err)});

User, post, and comment model in mongoose

I am making a forum app that is quite similar to Reddit. I am using mongoose here for schema design. I have some doubts regarding models that I have- User, Post and Comment.
Does the schema look all right of all the models?
In User, I want to show the friends on the user profile. Like when you go to his profile, there will be like Friends(200), and when I click the friend list will appear(like Facebook, then on clicking you can access friends' profiles). I haven't created Friend schema, but does it needed actually?
Question about comments. So far, I have the basic comment schema. What happens to the threaded comments or replies. How do I store them?
All the models that I have currently:
const userSchema = new Schema(
{
username: { type: String, required: true },
email: { type: String, reuired: true },
password: { type: String, required: true },
country: { type: String, required: true },
friends: [{ type: Schema.Types.ObjectId, ref: "Friend" }], // is it needed?
posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
},
{ timestamps: true }
)
const postSchema = new Schema(
{
title: { type: String, required: true },
description: { type: String, required: true },
user: { type: Schema.Types.ObjectId, ref: "User" },
slug: { type: String, slug: "title" },
upvotes: { type: Number },
downvotes: { type: Number },
city: { type: String }, // post will have a tag by the city like NewYork, LA etc.
},
{ timestamps: true }
)
const commentSchema = new Schema(
{
comment: { type: String, required: true },
post: { type: Schema.Types.ObjectId, ref: "Post"},
user: { type: Schema.Types.ObjectId, ref: "User"},
upvotes: { type: Number },
downvotes: { type: Number }
},
{ timestamps: true }
)
For the Second Question you don't need friend schema since friend is also a user.
For the first question, Why do intend to store all the posts of a user inside the User object as a list of posts, this would mean fetching 100s of posts even when something basic like username or email is required. Instead, you can place user_id in the Post Schema, helping to identify posts from a particular User.

How to sustainably organise user schema in mongoose

I have a user which should have the following fields and currently has following schema:
const UserSchema = new Schema(
{
email: {
type: String,
required: true,
index: { unique: true },
lowercase: true,
},
isVerified: { type: Boolean, default: false }, // whether user has confirmed his email
name: { type: String, required: false },
password: { type: String, required: true, minLength: 6 }, // object with next two included?
passwordResetExpires: Date,
passwordResetToken: String,
roles: [{ type: 'String' }], // Array of strings?
username: { type: String, required: false },
token: [{ type: String, required: false }], // used to send verification token via email
},
{ timestamps: true },
);
So yes, what is the world's default standard for organising user schemas. This schema's fields are pretty common, right?

Unique index not working on Mongoose schema

I have a schema setup like this:
var UserSchema = new Schema({
id: {type: String, required: true, unique: true, index: true, default: mongoose.Types.ObjectId},
name: { type: String, required: true },
email: { type: String, required: true, unique: true, index: true },
mobile: { type: String, unique: true, sparse: true },
password: { type: String, required: true }
});
Seems to work great except the email field is letting in duplicates, despite have unique:true set. I do the following:
User.create({
name: req.body.name,
email: req.body.email,
mobile: req.body.mobile,
password: password
}, function(err, user) {
if (err) return res.send({ invalid : true });
});
If req.body.email is a value that's already in the database, the query above should return err. But it doesn't, it creates the new user perfectly fine, resulting in duplicate emails in the database.
Why is this happening?
mongo and hence mongoose will assign an automatic id fields to your document. usually that is "_id".
Try removing the "id" from your schema to fix your issue.

Categories

Resources