How to populate array of objects with Mongoose - node.js

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

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

Is it possible to design such schema in MongoDB ? If not any suggestions?

I am trying to develop such a schema in MongoDB.
var subCategorySchema = new Schema({
_id: ObjectId,
name : String,
});
var categorySchema = new Schema({
name : String,
category : {
type : Schema.Types.ObjectId,
ref : 'subCategories'
},
});
var postSchema = new Schema({
name : String,
category : {
type : Schema.Types.ObjectId,
ref : 'categories'
},
subCategory : {
type : Schema.Types.ObjectId,
ref : 'categories'
}
});
The issue is that how can I directly populate sub category in post ?

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

Mongoose Finding data in Sub document

I have this model
//user notif schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var UserNotifSchema = new mongoose.Schema({
NotifType : {type : Number},
NotifData : {
User_source_id : {type : Schema.Types.ObjectId, ref : 'User'}, // for course, forking
Course_id : {type : Schema.Types.ObjectId, ref : 'Course'}, // for course
UserFile_id : {type : Schema.Types.ObjectId, ref : 'UserFile'} // for forking
},
NotifTarget : [
{type : Schema.Types.ObjectId, ref : 'User'}
],
Created_at : {type : Date, required : true, default : Date.now},
});
var UserNotif = mongoose.model('UserNotif', UserNotifSchema);
module.exports = UserNotif;
I create a model that contains user notification by NotifTarget. I want to get some notif to specific user and doing like this
var user_id = req.session.userLogin.UserId;
NotifModel.find({'NotifTarget' : user_id})
.populate('NotifTarget')
.exec(function(err, doc){
if (err){
res.send(err);
}
else{
res.send(doc);
}
})
This is ok when there only one array user_id in NotifTarget but return empty array when I give multiple data in NotifTarget. Are there any solution for this?

Mongoose: retrieving array of ObjectIds from collection

My database has following type of documents for Categories collection.
{
"_id" : ObjectId("56716afa403743492828aa07"),
"cat_name" : "watches",
"cat_parent_id" : [
ObjectId("56716afa403743492828aa01"),
ObjectId("56716afa403743492828aa03")
]
.........
}
I first created database with Robomongo, then I'm trying to fetch data using mongoose and created following Schema.
var categorySchema = new Schema({
'cat_name' : String,
'cat_parent_id' : [{ type : mongoose.Types.ObjectId }],
.......
});
but when I'm getting the result through following callback,
Categories.find(function(err,categories){........});
the cat_parent_id array is empty.
Edit:
When I replace mongoose.Types.ObjectId with Schema.Types.ObjectId or String,It works.Can anyone provide reason for that?
You need to add reference for the ObjectId type:
var categorySchema = new Schema({
'cat_name' : String,
'cat_parent_id' : [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Categories'
}],
.......
});

Resources