type Object Validation in Mongoose? - node.js

I am trying to do schema validation in mongoose of type object and array, but I am not able to do that. Here is the schema:
var alertEmailSchema = new alertEmailSchema({
templateId: { type: String, required: true,unique: true},
templateName : { type: String, required: true},
status: Boolean,
frequency : { type: Object, required: true},
recipientsEmailId : { type: [String], default: [], required: true},
subject : { type: String, required: true},
message : { type: String, required: true},
description : String,
createdDate : {type : Date, default : Date.now},
updatedDate : {type : Date, default : Date.now}
});
var schemaValidation = newAlertEmail.validateSync();
Please tell me how can I do the validation for this.

I assume you want something like this:
var frequency = new Schema({
count: {
type: Number
},
updateAt: {
type: Date
}
}, {
_id: false // this will not create _id for this schema
});
var alertEmailSchema = new Schema({
templateId: { type: String, required: true,unique: true},
templateName : { type: String, required: true},
status: Boolean,
frequency : frequency, //this can be an array also [frequency]
recipientsEmailId : { type: [String], default: [], required: true},
subject : { type: String, required: true},
message : { type: String, required: true},
description : String,
createdDate : {type : Date, default : Date.now},
updatedDate : {type : Date, default : Date.now}
});
Here, I created another schema known as frequency and used it in schema alertEmailSchema.

Related

is there a way to have object instances on mongo schema

I have been doing back end for a hospital prescription management and I used mongo and node for that.. when using the mongo schema, not knowing how many drugs will the doctor write I have to manually write all the drugs for the schema.. so is there a way to automate it .. am new to mongo so help me please.
const presmod = mongoose.Schema({
HospName : {
type: String,
required : true
},
DoctorId: {
type : String,
required : true
},
PatientName : {
type: String,
required : true
},
PatientId : {
type: String,
required : true
},
drugs : {
drug1 : {date:{type: Date, required: true},Name: {type: String, required: true}},
drug2 : {date:{type: Date, required: true},Name: {type: String, required: true}},
drug3 : {date:{type: Date, required: true},Name: {type: String, required: true}},
drug4 : {date:{type: Date, required: true},Name: {type: String, required: true}},
drug5 : {date:{type: Date, required: true},Name: {type: String, required: true}},
drug6 : {date:{type: Date, required: true},Name: {type: String, required: true}},
},
})
module.exports = mongoose.model("prescription", presmod)
instead of manually typing drug 1, drug 2 ... drug n ,.. is there a way to automate it?
using array you can define it like this:
drugs: [{
date: {
type: Date,
required: true
},
Name: {
type: String,
required: true
}
}]

How do I use nested schemas in mongoose, using 'type', to create arrays?

I am trying to create a nested mongoose schema that uses 'type' to create a nested array.
The schema that I think I am having an issue with is "chorePerson".
Here is the data that I am trying to put into a schema:
{
"chart": [
{
"ordinal": 0,
"chorePerson": [
{
"person": "emily",
"chore": "Catbox"
},
{
"person": "Steve",
"chore": "Dishes"
}
]
}
]
Here is my current schema. Note the use of "type" for "chart" and "chorePerson"
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const chorePersonSchema = new mongoose.Schema({
person: {type: String, requried: true},
chore: {type: String, required: true},
});
const chartSchema = new mongoose.Schema({
ordinal: {type: Number, required: true},
chorePerson:{ type: chorePersonSchema },
});
// create the schema
const ChoreChartSchema = new Schema({
affiliation: {type: String, required: true},
currentWeekNumber: {type: Number, required: true},
currentYear: {type: Number, required: true},
chart:{ type: chartSchema },
date: {type: Date, default: Date.now},
})
module.exports = ChoreChart = mongoose.model('cm_chorechart', ChoreChartSchema)
When I run my code this is what I get before the crash:
{ _id: 5c742ed116a095522c38ddfc,
affiliation: 'family',
currentYear: 2019,
currentWeekNumber: 9,
date: 2019-02-25T20:26:33.914Z,
chart: [ { ordinal: 0, chorePerson: [Array] } ] }
I think... chorePerson is causing the error... but I don't know how to fix it.
Here is the exception:
(node:6728) UnhandledPromiseRejectionWarning: ObjectExpectedError: Tried to set nested object field `chart` to primitive value `[object Object]` and strict mode is set to throw.
What I have tried
I tried this schema:
const chartSchema = new mongoose.Schema({
ordinal: {type: Number, required: true},
chorePerson : [{
person : String,
chore : String
}]
});
Update:
OK... so I went back to basics and this works, but it's not how I want the final schema to be. Can anybody help out with nesting this ?
// create the schema
const ChoreChartSchema = new Schema({
affiliation: {type: String, required: true},
currentWeekNumber: {type: Number, required: true},
currentYear: {type: Number, required: true},
// chart:{ type: chartSchema },
chart:[{
ordinal: 0,
chorePerson : [{
person : String,
chore : String
}]
}],
date: {type: Date, default: Date.now},
})
Turns out it was easier than I thought:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const chorePersonSchema = new mongoose.Schema({
person: {type: String, requried: true},
personID: {type: String, required: true},
chore: {type: String, required: true},
choreID: {type: String, required: true},
});
const chartSchema = new mongoose.Schema({
ordinal: {type: Number, required: true},
chorePerson : [{ type:chorePersonSchema }]
});
// create the schema
const ChoreChartSchema = new Schema({
affiliation: {type: String, required: true},
weekNumber: {type: Number, required: true},
year: {type: Number, required: true},
chart:[{type: chartSchema}],
date: {type: Date, default: Date.now},
})
module.exports = ChoreChart = mongoose.model('cm_chorechart', ChoreChartSchema)

Index of username_1 gets created in mongoDB although no username in the Schema/Model

Hello, I hope this question ain't stupid, but I have a problem with Nodejs/mongoose/MongoDB.
var SportsSchema = new Schema({
title: String,
internalTitle : String,
semester : String ,
uniqueIdent : { type : String, unique : true, index : true },
sportsType: String,
kindOfSport: String,
description: String,
location: String,
numberOfParts: Number,
recurrence: String,
weekDay1: {type: String, default: 'empty'},
weekDay2: {type: String, default: 'empty'},
startTime1: {type: String, default: 'empty'},
startTime2: {type: String, default: 'empty'},
sportDates: [{
type: Date
}],
specDates: [{
type: String
}],
timeFrame: [{
type: Date
}],
created: {type: Date, default: Date.now },
});
This is the Schema. Only uniqueIdent is unique and indexing. As soon as the nodeJS app starts, the mongoDB collection has the following indexes: _id, uniqueIdent and username. While the first two are expected, the third one is flabbergasting me.
There is a username in the other schema that i am using, but that shouldn't influence this one, should it.
Any help would be appreciated, if more information is necessary, I will happily provide it.
other schema:
var UserSchema = new Schema({
username: {type: String, lowercase: true, unique: true, match: [/\S+#\S+\.\S+/, 'ist nicht erlaubt']},
email: {type: String, lowercase: true, unique: true, match: [/\S+#\S+\.\S+/, 'ist nicht erlaubt']},
firstname :String,
lastname: String,
password: String,
//admin: {type: Boolean, default: false },
permissionLevel: {type: String, default: 'user' },
tr_tmp: {type: Boolean, default: 'false'},
classOne: {type: String, default : 'empty' },
classTwo: {type: String, default : 'empty' },
classThree: {type: String, default : 'empty' }
});

Schema Association in Mongoose

I have 2 models:
Here is the User Model:
const userSchema = new mongoose.Schema({
email: { type: String, unique: true, required: true },
password: { type: String, required: true },
passwordResetToken: String,
passwordResetExpires: Date,
facebook: String,
twitter: String,
tokens: Array,
profile: {
name: String,
gender: String,
location: String,
website: String,
picture: String
}
}, { timestamps: true });
And here is the Revive Model:
const reviveSchema = new mongoose.Schema({
reviveShowName: {type: String, required: true},
reviveTitle: {type: String, required: true},
reviveCategory: {type: String, required: true},
reviveGoal: {type: Number, required: true},
revivePhoto: {type: String, required: true},
reviveVideo: {type: String},
reviveStory: {type: String},
author: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
name: String
}
}, { timestamps: true });
In the Revive model, I'm trying to the reference the author and get the author's id and that works... How do I also get the name from profiles -> name...? Clearly name: String is wrong...
Mongoose relations work, based on the ref and type value of the nested object. In your case you have associated the id property of author to point to the User model.
If you want to populate the author with the user information, you should just do :
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
Then in your query you just use populate
Revive.find({})
.populate( 'author' )
.exec( function( error, docs ) {
console.log( docs ); // will have `[{author:{profile:{...}}}]` data
} );

Node.js - Create Relationships with Mongoose from different file

I have two Schemas Products and Users in different files. Products are belong to User and User have many Product
The Problem is, I have try to use Populate but somehow it return not what I expected.
here is my Schema for Product on models products.js
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var users = require('../models/users');
var Product = mongoose.Schema({
user_id : {type: String, required: true },
category_id : {type: String, default: null},
title : {type: String, required: true },
content : {type: String, default : "" },
pictureUrls : Array,
counter : {type : Number, default : 0},,
lowercaseTitle : {type: String, default : null },
_user : { type: Schema.Types.ObjectId, ref: users.User }
});
Product.set('toObject', {
getters: true,
virtuals: true
});
module.exports = mongoose.model('Product', Product)
and this is my Schema for User on models users.js
var mongoose = require('mongoose');
var User = mongoose.Schema({
firstName : {type: String, default: "" },
lastName : {type: String, default: "" },
username : {type: String, required: true },
email : {type: String, required: true },
password : {type: String, default: "" },
bio : {type: String, default: "" },
website : {type: String, default: "" },
phone : {type: String, default: "" },
gender : {type: String, default: "" },
birthDate : {type: Date, default: null },
avatarUrl : {type: String, default: "" },
verified : {type : Boolean, default : false}
});
User.set('toObject', {
getters: true,
virtuals: true
});
module.exports = mongoose.model('User', User);
currently I am using method find by calling each Models
User.findOne({"sessionToken" : bearerHeader}, function (err, user){
Product.find({"user_id" : user._id}, function (err, products){
console.log(products);
});
});
but it takes time and became problem if there related to another models.
I'm calling populte with this
Product.findOne({}).populate('_user').exec(function(err, p){
console.log(p);
});
but attribute _user was not set and undefined
any help?
Thanks

Resources