Using Mongoose to access values in an array - node.js

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.

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

node js mongoose find inside nested mixed property?

I have a mongoose schema like this.
var schema = new mongoose.Schema({
t: {type: Date, required: true},
o: {type: String, required: true},
d: {type: mongoose.Schema.Types.Mixed, required: true}
}
the objects in mongoDb are like this.
{
"_id" : ObjectId("5d36948b7f40460dd0d28934"),
"t" : ISODate("2019-07-23T05:00:59.518Z"),
"o" : "u",
"d" : {
"room" : "5c0508cd12e0fc3310a8ba00",
"noOfTimesSwapped" : 4,
"modifiedAt" : "2019-07-23T05:00:59.517Z",
"modifiedBy" : "5c73d5f2e4c2754e0cd5246a",
"p" : {
"_id" : "5d35bac67660ad2dd8fbb57d"
}
}
}
I want to get the records which matches with the _id of the 'p' field which is a property of d.
I have tried to get records using the following criteria, but that does not work.
MyModel.find({ 'd.p._id': id }, function (err, docs) {});

Setting default values to array of objects in mongoose

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 });

Mongoose dup key

I'm getting a duplicate key error and not sure why.
I have the following schema:
var walletSchema = mongoose.Schema({
currencyName : {type : String, required : true, unique : true},
amount : {type : Number, default : 0}
}, {strict : false});
// define the schema for our user model
var userSchema = mongoose.Schema({
local : {
username : { type: String, required: true, unique: true },
password : { type: String, required: true, unique : true },
email : { type: String, required: true, unique: true },
country : { type: String, required: true },
inventory : {
food : { type : Number, default : 0},
energyDrinks : { type : Number, default : 0 }
},
wallet : [walletSchema],
lastAttackedAt : { type: Date, default: Date.now },
lastJobChange : {type: Date, default: '03/30/1988' },
lastWorked : {type: Date},
referredBy : {type : String, default : 'Admin'},
energy : { type: Number, default: 100 },
energyUpdatedAt : { type : Date, default: Date.now },
resetPasswordToken: String,
resetPasswordExpires: Date
}
},{timestamps : true});
I create a new user with this code :
...
newUser.local.username = capitalizeUser(username);
newUser.local.password = newUser.generateHash(password);
newUser.local.email = req.body.email;
newUser.local.country = req.body.country;
newUser.local.wallet.push({
// Create the default currencies
currencyName: 'Euro',
}, {
currencyName: 'Gold',
}, {
currencyName: result.countryCurrency
}
);
// save the user
newUser.save(function(err) {
if (err)
throw err;
return done(null, newUser);
});
Everything works fine for the first user however if I try to make another user I get MongoError: insertDocument :: caused by :: 11000 E11000 duplicate key error index: xyz.users.$local.wallet.currencyName_1 dup key: { : "Euro" }.
Why is this happening, doesn't each user has it's own wallet? How should I handle it, keep in mind that there are about ~230 currencies available for each user.
currencyName : {type : String, required : true}
Remove unique from there and you will be good to go. Mongo checks unique keys for collection. In your case walletSchema collection will have a lot of same values so that's why it's gives error.
As your currencyName has been set unique so it has to be different for each user you save. In fact you with this schema you won't even be able to have two users from the same country.
So to avoid this you need to remove the unique keyword from you schema and it is done. It then looks something like this.
var walletSchema = mongoose.Schema({
currencyName : {type : String, required : true},
amount : {type : Number, default : 0}
}, {strict : false});

Mongoose Sorting

I have a problem with displaying data with sorting. Here is my query,
Activity.find({"user_id": sesUser._id}, {}, {offset: 0, limit : 5, sort:{createdAt:1}}, function (e,a){
...
});
I have data about 252 length, and my latest data is 9 June 2015. If i use this query i only get data from 5 June 2015/ last week data and not get the latest data, but if i not using sorting, the latest data is appear.
I have used this query below but turns out the result is same.
Activity.find({"user_id" : sesUser._id}).sort("createdAt").exec(function(err,a){
...
});
Any help? I'm using Mongoose v3
-- edited --
This is my Activity Schema / Model
var mongoose = require('mongoose');
var Activity = mongoose.Schema({
sender_id : {type: String, required: true },
user_id : {type: String, required: true },
product_id : {type: String, default : "" },
type : {type: String, required: true },
createdAt : {type: String, default : new Date()}
});
module.exports = mongoose.model('Activity', Activity);
`createdAt : {type: Date, default : new Date()}`
Type Date not string man
It will automatically create the createdAt and updatedAt
var options={
timestamps: true
}
var Activity = mongoose.Schema({
sender_id : {type: String, required: true },
user_id : {type: String, required: true },
product_id : {type: String, default : "" },
type : {type: String, required: true }
},options);

Resources