node js mongoose find inside nested mixed property? - node.js

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

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.

update object inside array that is inside collection

I need to update field "rightAnswer" in object inside array that is inside collection.
How can I change boolean of specific comment to true for right question.
In Angular I pass id of question and id of comment to backend. But on the backend I don't know how to update that field. I use MEAN stack.
Question schema:
var questionSchema = new mongoose.Schema({
title: {type : String, default : '', trim : true},
text: {type : String, default : '', trim : true},
publisher_id: {type : mongoose.Schema.ObjectId, ref : 'User'},
answers: [{
body: { type : String, default : '' },
user: { type : mongoose.Schema.ObjectId, ref : 'User' },
rightAnswer: { type : Boolean, default: false },
createdAt: { type : Date, default : Date.now }
}],
date : {type : Date, default : Date.now}
});
My route in express:
Question.update({_id: req.body.question._id}, {"answers._id": req.body.answer._id}, {$set: {"answers.$.rightAnswer": true} }, function(req, data){
res.json(data);
});
Solution:
Question.update({_id: req.body.question._id,
"answers": {$elemMatch: {_id: req.body.answer._id}}},
{$set: {"answers.$.rightAnswer": true}},
function(req, res){});
Question.update({_id: req.body.question._id,
"answers": {$elemMatch: {_id: req.body.answer._id}}},
{$set: {"answers.$.rightAnswer": true}},
function(req, res){});

How to populate array of objects with Mongoose

I have the following schemas in mongoose:
var documentsSchema = new Schema({
"document" : {
"_project" : {
type : Schema.ObjectId,
ref : 'Projects'
},
"_addedBy" : {
type : Schema.ObjectId,
ref : 'Users'
},
"_associateUsers" : [{
type : Schema.ObjectId,
ref : 'Users'
}],
"_codes" : [{
type : Schema.ObjectId,
ref : 'Codes'
}],
"paragraphTitle" : String,
"paragraphText" : String,
"memos" : [
{
"_addedBy" : {
type: Schema.Types.ObjectId,
ref: 'Users'
},
"memoData" : String
}
]}});
and the Codes:
var codesSchema = new Schema({
"code" : {
"_addedBy" : {
type : Schema.ObjectId,
ref : 'Users'
},
"codeText" : String,
"codeWeight" : Number
}});
I need to populate _codes.codeText (or codes fields) of the all elements of the array, but looks like I am not doing it properly.
Documents.find({
"document._project": element._id
}).
populate('document._codes.code','codeText').
exec(function (err, result) { .... }
this and various tries with populate arguments are either not populating the fields or not returning any data.
What am I doing wrong?
You have defined the schema, but not the model. The _codes has a ref to the model Codes but it doesn't exists. When you call .populate with the first two params it assumes that the model is Codes (taked from reference)
To fix this, toy need to add:
mongoose.model('Codes', codesSchema);
mongoose.model('Documents', documentsSchema);
Maybe you need to do the same with Users
See the complete documentation for populate here
P.S. A recommendation: If you are defining an schema for codes or whatever you don't need to define again the name of the object as part of the same schema, look:
From this
//your style
var catsSchema = new Schema({
"cat" : {
"attr1" : {type: ...},
"attr2" : {type: ...}
}
});
to this
//obviously attr1 and attr2 are part of cat object/document
var catsSchema = new Schema({
"attr1" : {type: ...},
"attr2" : {type: ...}
});

Resources