Setting default values to array of objects in mongoose - node.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var patientSchema = new Schema({
resourceType : {type :String, default : 'Patient' },
id : {type : String, default : 'example'},
text : [{
status : {type : String, default : 'generated'},
div :{type : String, default :'<div> Something </div>'}
}],
active : {type : String, default : 'true'},
identifier : [{
use : {type : String, default : 'official'},
system : {type : String, default : 'urn:oid:1.2.36.146.595.217.0.1'},
assinger :[{
display : {type : String, default : 'Acme Healthcare'},
}]
}],
name: [{
use : {type : String, default : 'official'},
first_name : {type : String, default : ''},
second_name : {type : String, default : ''}
}],
gender :{type : String, default : ''},
birthDate :{type : String, default : ''},
telecom : [{
system : {type : String, default : ''},
value : {type : String, default : ''}
}],
address : [{
use : {type : String, default : 'official'},
text : {type : String, default : ''},
city : {type : String, default : ''},
district : {type : String, default : ''},
state : {type : String, default : ''},
postalcode :{type : String, default : ''}
}]
});
var patients = mongoose.model('Patients',patientSchema);
module.exports = patients;
This is my model class, i'm sending values through post-man tool,
The default values inside the array of fields eg.
text : [{
status : {type : String, default : 'generated'},
div :{type : String, default :'<div> Something </div>'}
}],
the status and div are not storing the default values
i need to store the values of status and div as default!

You could use a sub-scheme/document instead!
var patientTextSchema = new Schema({
status : {type : String, default : 'generated'},
div :{type : String, default :'<div> Something </div>'}
});
... ommited for clarity
var patientSchema = new Schema({
text: [patientTextSchema]
})
This way you you can do patient.text.push({}) for adding a default patientTextSchema, or patient.text.push({status: "another_status"}) for a (partially) filled scheme.
Source: http://mongoosejs.com/docs/subdocs.html

You can use the following way to create Array of Objects with a default in mongoose:
const organisationSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
brands: {
type: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'brand'
}
],
default: []
},
users: {
type: [
{
type: mongoose.Schema.Types.ObjectId,
ref: 'user'
}
],
default: []
}
}, { timestamps: true });

Related

how to update specific subdocument in array with mongoose

postSchema
let postSchema = new mongoose.Schema({
data : Buffer,
contentType : String,
caption : String,
likes : [mongoose.ObjectId],
likesCount : {type :Number, default : 0},
comment :[{userId :mongoose.ObjectId, cmnt : String, reply :[{}]}],
commentCount : {type :Number, default : 0},
date : {type : Date, default: Date.now}
})
userSchema
let userSchema = new mongoose.Schema({
qr : {
data : Buffer,
contentType : String
},
profile_pic:{
data:Buffer,
contentType : String
},
first_name:String,
last_name:String,
email:{
type:String,
unique:true
},
mobile_number:Number,
DOB : Date,
gender:{
type : String,
enum : ["Male","Female","Other"]
},
password : {
type : String
},
address:{
city : String,
state : String
},
followers : {
type : [mongoose.ObjectId]
},
followersCount : {
type : Number,
default : 0
},
following : {
type : [mongoose.ObjectId]
},
followingCount : {
type : Number,
default : 0
},
//this is my post schema
posts : [postSchema],
postsCount :{type :Number, default : 0},
reset_password_token : {
OTP:Number,
is_varify_password_token : {
type:Boolean,
default : false
},
time : {
type : Date,
}
}
})
** 1) i want to find specific user
2) after finding user i want to find and update specific post (caption) in array of posts **
i have tried but not working
await USERMODEL.findOneAndUpdate({_id:req.user._id,posts:{$elemMatch:{_id: req.params.postId}}},{"posts.$.caption ":caption})mongodb document image
PLEASE HELP I AM NEW TO MONGODB
**by mistake I have pasted some code out of block please do not mind **
It looks like your post is mostly code; please add some more details

Mongoose virtuals in array of subdocument

Is there a way to "get" the value a document's field in the subdocuments?
book_id is in the main document,how to get the value of it here
'''
const ExtraElements_Schema = new Schema({
label : {type : String, requires : true},
page : {type : Number},
id_resource : {type : Number, required : true},
description : {type : String}
},{toJSON : {virtuals : true , getters : true}})
ExtraElements_Schema.virtual('path').get(function(){
const host = global.gConfig.thisServerHost;
return `${host}/${this.book_id???}/${this.id_resource}`
})
const Extra_Schema = new Schema({
label : {type : String, required : true},
book_id : {type : Number},
id_extra : {type : Number, required : true},
extras : [ExtraElements_Schema]
})
You can use virtuals for this too.
ExtraElements_Schema.virtual('book', {
ref: bookTableName,
localField: 'book_id',
foreignField: '_id', // Change this if it's not the id that is saved
justOne: true
});
And one thing that bugged me a little I couldn't see the virtuals with console.log I should always use console.log(model.toJSON()) to see the virtuals

Using Mongoose to access values in an array

I am trying to write a project app that monitors medical data implemented using a MEAN stack. I intend to simulate the data by sending a 'vitalsTick' about every second. These are stored as an array of subdocuments in the patient document.
var mongoose = require('mongoose');
var vitalsTickSchema = new mongoose.Schema({
time : {type: Number, min : -299, max: 300, required: true},
pulse : {type: Number, required:false},
rhythm : {type: String, required: false},
resp : {type: Number, required: false},
spo2 : {type: Number, required: true}
});
var VitalsTick = mongoose.model('vitalsTick', vitalsTickSchema, 'vitalsTick');
module.exports = VitalsTick;
and
var vitalsTickSchema = mongoose.model('vitalsTick').schema;
var patientRecordSchema = new mongoose.Schema({
name : {type: String, required: true},
mrn : {type: Number, required: true},
dob : {type: Date, required: false},
address : {type: String, required: false},
mhx : {type: [{history : {type: String, required: false}}]},
vitalTicks : [vitalsTickSchema]
});
var PatientRecord = mongoose.model('patientrecord', patientRecordSchema, 'patients');
module.exports = PatientRecord;
I have written some python to generate test data in json that validates using jsonlint and then imported to mongodb. Before moving to the next step of development, I want to ensure the schemas work as planned. Using Mongo:
> db.patients.find()
{ "_id" : ObjectId("59c2fc69b9e18eb6ad18c063"), "name" : "Testie
McTestface", "mrn" : "11111111", "dob" : "", "address" : "", "mhx" : [ { } ],
"vitalTicks" : [ { "time" : 0, "pulse" : 75, "rhythm" : "sinus",
"rr" : 20, "SpO2" : 96 }, ... ] }
My problem is this:
> db.patients.find({vitalTicks: {time : {$eq :0}}},{'vitalTicks.$':1})
>
As far as I can tell should return
{ "_id" : ObjectId("59c2fc69b9e18eb6ad18c063"), "vitalTicks" : [ {
"time" : 0, "pulse" : 75, "rhythm" : "sinus",
"rr" : 20, "SpO2" : 96 } ] }
But it returns nothing.
Cheers.
No, actually it is an array of embedded documents, the following query makes the job:
db.patients.find({"vitalTicks.time" : 0}, {"vitalTicks.$":1})
Hope this helps.

Mongoose- How to use discriminators in subdocument

I want the output to be like this
var FeedSchema = new Schema({
timestamp : {type : String, required : true},
feed_type_code : {type : Number, required : true},
gender : {type : String, required : true},
feed_item : Article || Tip || etc.
}
Hence, I understand I have to use discriminators. I followed the following SO answer
Here is what I did:
var feed_type = {discriminatorKey : 'feed_item'};
var FeedSchema = new Schema({
timestamp : {type : String, required : true},
feed_type_code : {type : Number, required : true},
gender : {type : String, required : true}
}, feed_type);
var TipSchema = new Schema({
tip : {type : String, required : true},
subtip : {type : String, required : true},
display_count : {type : Number},
likes : {type : Number}
}, feed_type);
var ArticleSchema = new Schema({
title : {type : String, required : true},
english_title : {type : String, required : true},
image_url : {type : String, required : true},
article_text : {type : String, required : true},
english_article_text : {type : String},
author : {type : String},
english_author : {type : String}
}, feed_type);
Here is how I am saving the document:
var article = new Article({
title : req.body.title,
english_title : req.body.english_title,
image_url : req.body.image_url,
article_text : req.body.article_text,
english_article_text : req.body.english_article_text,
author : req.body.author,
english_author : req.body.english_author
});
var feed = new Feed({
gender : req.body.gender,
timestamp : moment().valueOf(),
feed_type_code : 9002,
feed_item : article
});
feed.save(function(err, doc){
if(err){
res.json({success : -1});
return;
}
res.json({success : 1, feed : doc});
});
I am not getting the article output for this:
{
"success": 1,
"feed": {
"__v": 0,
"gender": "female",
"timestamp": "1481460218959",
"feed_type_code": 9002,
"_id": "584d49faa6ff3a23bc868ab3"
}
}
I am new to Nodejs. I would appreciate if you can point out the error.
in the model file add these lines
var Feed = mongoose.model('Feed', FeedSchema, 'feed');
var Article = Feed.discriminator('Article', ArticleSchema);
var Tip = Feed.discriminator('Tip', TipSchema);
module.exports = {
Feed : Feed,
Article : Article,
Tip : Tip
}
This is how you save the document. You don't need to create a separate Feed object.
var article = new Article({
gender : req.body.gender,
timestamp : moment().valueOf(),
feed_type_code : 9002,
title : req.body.title,
english_title : req.body.english_title,
image_url : req.body.image_url,
article_text : req.body.article_text,
english_article_text : req.body.english_article_text,
author : req.body.author,
english_author : req.body.english_author
});
article.save(function(err, doc){
if(err){
console.log(err);
res.json({success : -1});
return;
}
res.json({success : 1, feed : doc});
});

Error when setting field as null in Mongoose

I am using MongooseJS. I am getting the error below:
{ message: 'Cast to ObjectId failed for value "" at path "parent"',
name: 'CastError',
type: 'ObjectId',
value: '',
path: 'parent'
}
I don't want to set a parent for this object. Where am I wrong? What should I do?
Update:
var category = new Category(req.body)
if(typeof category.parent === 'undefined'){
category.parent=undefined;
}
And the category schema is:
var CategorySchema = new Schema({
name: {
tr: {type : String, default : '', trim : true},
en: {type : String, default : '', trim : true}
},
description: {
tr: {type : String, default : '', trim : true},
en: {type : String, default : '', trim : true}
},
subcategories:[{type : Schema.ObjectId, ref : 'Category', null: true}],
parent: {type : Schema.ObjectId, ref : 'Category', null: true},
products:[{type : Schema.ObjectId, ref : 'Product'}],
images : [String],
order: {type : Number, default: 0},
createdAt : {type : Date, default : Date.now},
locale: {type : String, null: false}
})
My jade code is:
.controls
select#parent(name="parent")
option(value="") Select
each cat in categories
- if (category.subcategories.map(function(e) { return e.id; }).indexOf(cat.id) != -1)
option(value=cat.id, selected) #{cat.name.tr}
- else
option(value=cat.id) #{cat.name.tr}
So if user do not select a parent, it sends "" to server and server gives that error.
The error states you can't cast the type you're trying to set into the category.parent property as it's expecting an ObjectId. I'd expect that the parent field value coming through req.body is not an ObjectId
Also, all properties are defined on a MongooseJs model and won't be undefined.
You need to set it to null:
category.parent = null;
This will clear the value.
Old question, but I got the same issue and want to share the answer. Before creating the Category-Object you have to manually delete the parent-property from req.body, if it's not setted with a valid value:
if (req.body.parent == "")
delete req.body.parent; // or req.body.parent = null;
var category = new Category(req.body);
Setting it afterwards to null won't work - don't ask me why.

Resources