I have to populate students in my data,
"attendances" : [
{
"_id" : ObjectId("5851702b9accfc6e70d55107"),
"students" : [
{
"student" : ObjectId("5850e6d596d4de3c1f4a0614"),
"_id" : ObjectId("5851702b9accfc6e70d55109"),
"ispresent" : "No"
}, }]
My schema,
attendances: [{
date: {
type: String,
default: ''
},
created_by: {
type: Schema.ObjectId,
ref: 'Employee'
},
students: [{
student: {
type: Schema.ObjectId,
ref: 'Student'
},
ispresent: {
type: String,
default: ''
}
}]
}],
Attendance.findById(id).populate('attendances.students')
I tried the above way but fails.Can any one please suggest help.Thanks.
You can write your population predicate by the dot notation while you're digging deeper into both object or array to refer at the end to another valid schema of type Schema.Types.ObjectId, so according to your mentioned schema, you query would be as follow:
Attendance.findById(id).populate('attendances.students.student')
Related
We are struct at one mongodb point which I would like to describe here.
We are using mongoose 5.4 and create a model like below :
var userSchema = mongoose.Schema({
id:{ type: Number, default: 1 },
first_name: String,
last_name: String,
mail: String,
password: String,
dob: { type: String, default: '' },
gender: { type: String, default: '' },
profile_photo: { type: String, default: '' },
ethnicity: { type: String, default: '' },
contact_number: { type: String, default: '' },
user_type: Number,
address1: { type: String, default: '' },
address2: { type: String, default: '' },
area: { type: String, default: '' },
city: { type: String, default: '' },
country: { type: String, default: '' },
postcode: { type: String, default: '' },
business_name: { type: String, default: '' },
ip_address: String,
status: Number,
tag_line: { type: String, default: '' },
is_influencer: Number,
wallet_id: String,
token_balance: { type: Number, default: 0 },
point_balance: { type: Number, default: 0 },
badges: [String],
membership: { type: Schema.Types.ObjectId, ref: 'Membership' },
transaction: [{ type: Schema.Types.ObjectId, ref: 'Transaction' }],
property: [{ type: Schema.Types.ObjectId, ref: 'Property' }],
reviews: [{ type: Schema.Types.ObjectId, ref: 'Review' }],
created_date: String,
});
var User = mongoose.model('User', userSchema);
var propertySchema = mongoose.Schema({
id: Number,
property_name: String,
address1: String,
area: String,
post_code: String,
category: [{ type: Schema.Types.ObjectId, ref: 'Category' }],
category_id: [Number],
property_desc: String,
property_images: String,
slug : String,
user_id: Number,
business_key: String,
user: { type: Schema.Types.ObjectId, ref: 'User' },
reviews: [{ type: Schema.Types.ObjectId, ref: 'Review' }],
status: Number,
is_claimed: Number,
created_date: String,
});
var Property = mongoose.model('Property', propertySchema);
var categorySchema = mongoose.Schema({
id: Number,
category_name: String,
status: Number,
user: { type: Schema.Types.ObjectId, ref: 'User' },
property: [{ type: Schema.Types.ObjectId, ref: 'Property' }],
created_date: String,
updated_date: String
});
var Category = mongoose.model('Category', categorySchema);
we are also using async-await for this project. we are fetching locations using below method to get location data as well User and Category.
sortClause = {};
sortClause.user=parseInt(-1);
let properties = await Property.find({'status':{$in:[1,2]}}).populate({path: 'user',
model: 'User',select: 'first_name last_name mail contact_number'}).populate({path: 'category',
model: 'Category',select: 'category_name id'}).sort(sortClause).skip(skip).limit(perpage).exec();
so when we get data in properties object after the execution of above line we are getting properties but as we are sorting by user's column of property model it does fetch data properly. It sorts on objectID and we would like to fetch on user's first_name.
I have tried by specifing `{'user.first_name':-1} in sort order but it doesn't work at all.
When we sort on string or Number column it works fine, but here my expected result will be bit different, Here we would like apply sort on user.first_name (Here in above example user is the ObjectId column which populate Users data and I would like to sort on first_name column of user)
How can we get properties based on user's first_name column? Is there any suggestion for this problem.
You can try below aggregation from mongodb 3.6 and above
Property.aggregate([
{ "$match": { "status": { "$in": status }} },
{ "$lookup": {
"from": "users",
"let": { "user": "$user" },
"pipeline": [
{ "$match": { "$expr": { "$eq": [ "$_id", "$$user" ] } } },
{ "$project": { "first_name": 1, "last_name": 1, "mail": 1, "contact_number": 1 }}
],
"as": "user"
}},
{ "$lookup": {
"from": "categories",
"let": { "category": "$category" },
"pipeline": [
{ "$match": { "$expr": { "$in": [ "$_id", "$$category" ] } } },
{ "$project": { "category_name": 1, "id": 1 }}
],
"as": "category"
}},
{ "$unwind": "user" },
{ "$sort": { "user.first_name": -1 }},
{ "$skip": skip },
{ "$limit": perpage }
])
I'm trying to update Sub-Sub Array item in MongoDB. I want to update the Comments(Comment field) inside the Slides array.
Slides--> Comments--> comment
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
var AttachmentSchema = new Schema({
FileName: String,
InternalName: String,
FileType: String,
InternalName: String
});
mongoose.model('Attachment', AttachmentSchema);
var SessionSchema = new Schema({
SessionTitle: String,
Chairperson: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
StartDateTime: { type: Date, required: true },
Duration: Number,
Attendees: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
AcceptOrReject: {
Comment: String,
Reason: String,
CreatedDate: Date,
UserId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
Status: String
},
Slides: [{
Seq: Number,
Details: String,
attachement: AttachmentSchema,
TarasulLetterDetails:{
MailObjectId: String,
Description: String,
Subject: String,
TarasulLetterUrl: String
},
Comments: [{
Comment: String,
DateTime: Date,
UserId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
IsFromOnline : String
}],
SurfaceAttachement: [{
FileName: String,
InternalName: String,
FileType: String,
}]
}],
Status: String,
CreatedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
CreatedDate: { type: Date, required: true },
ModifiedDate: Date,
SentDate: Date,
Comments: [{
Comment: String,
DateTime: Date,
UserId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' }
}],
Notifications: [{
UserId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
CreatedBy: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
AlertType: String,
AlertMessage: String,
DateTime: { type: Date, required: true },
IsAcknowledged: Boolean
}]
});
mongoose.model('Session', SessionSchema);
Below is the sample data.
> db.sessions.find({"_id": ObjectId('5af7bcdff107cb7a105243f5')}).pretty();
{
"_id" : ObjectId("5af7bcdff107cb7a105243f5"),
"SessionTitle" : "Project Status Meeting",
"Duration" : 60,
"StartDateTime" : ISODate("2018-05-15T05:15:00Z"),
"CreatedBy" : ObjectId("5aead4431a7ecc7230fb249a"),
"Status" : "APPROVED",
"CreatedDate" : ISODate("2018-05-13T04:19:43.050Z"),
"Notifications" : [
{
"IsAcknowledged" : false,
"DateTime" : ISODate("2018-05-14T09:15:23.385Z"),
"AlertMessage" : "Attendee updated",
"AlertType" : "Attendee",
"UserId" : ObjectId("5aead4a81a7ecc7230fb249c"),
"_id" : ObjectId("5af953ab67f3be54d4256f35")
},
],
"Comments" : [ ],
"Slides" : [
{
"Seq" : 1,
"Details" : "<p>Project Meeting</p>\n",
"_id" : ObjectId("5af7bcdff107cb7a105243f6"),
"Comments" : [
{
"_id" : ObjectId("5b45b854d217f62010fea8e7"),
"DateTime" : ISODate("2018-07-11T07:53:40.967Z"),
"IsFromOnline" : "3047",
"UserId" : ObjectId("5aead4431a7ecc7230fb249a"),
"Comment" : "test 123"
},
{
"_id" : ObjectId("5b45b89e7c32803a282e44db"),
"IsFromOnline" : "3043",
"DateTime" : ISODate("2018-07-11T07:58:22.648Z"),
"UserId" : ObjectId("5aead4431a7ecc7230fb249a"),
"Comment" : "new comments"
}
]
},
{
"Details" : "<p>second side</p>\n",
"Seq" : 2,
"_id" : ObjectId("5af7c843f107cb7a105243f7"),
"Comments" : [
{
"_id" : ObjectId("5b45b9bc569a4b284074fd08"),
"IsFromOnline" : "92179",
"DateTime" : ISODate("2018-07-11T08:03:01.851Z"),
"UserId" : ObjectId("5aead4431a7ecc7230fb249a"),
"Comment" : "test comments 123434343434343"
}
]
}
],
"Attendees" : [
ObjectId("5aead4a81a7ecc7230fb249c")
],
"Chairperson" : [
ObjectId("5aead4701a7ecc7230fb249b")
],
"__v" : 0,
"AcceptOrReject" : [
{
"Reason" : "More changes neened",
"Status" : "APPROVED",
"UserId" : ObjectId("5aead4701a7ecc7230fb249b"),
"CreatedDate" : ISODate("2018-05-14T09:15:23.385Z"),
"Comment" : "Will disucuss in next meeting"
}
]
}
For e.g i want to update Session "_id" : ObjectId("5af7bcdff107cb7a105243f5")
having Slides with Seq :1 and Comment from 'new comments' to 'Updated comments' with "IsFromOnline" : "3043".
i tried below and some other stuff, but it doesn't seem to work.
Session.update({
$and: [{
"_id": req.body.SessionId,"Slides.Seq": req.body.SeqNo
},
{
'Slides.Comments': {
$elemMatch: {
IsFromOnline: req.body.IsFromOnline
}
}
}
]
}, {
$set: {
'Slides.Comments.$.Comment': 'Updated comments'
}
})
i want to sum each values of ObjectId field in relationship with moongose..
I have this:
`var wineSchema = new Schema({
name: { type: String },
code: { type:String},
type: {
type: String,
enum: ['Red','Rose','White']
},
winery: { type: String },
grape_type: { type: String },
year: { type: Number },
alcohol: { type: Number },
rates: [{ type: Schema.ObjectId, ref: "Rate" }],
Comments: [{ type: Schema.ObjectId, ref: "Comment" }],
});`
And this:
`var rate = new Schema({
user : { type: Schema.ObjectId, ref: "User" },
userName : {type: String},
wineName : { type: String},
rating : { type: Number}
});`
I want sum total values of each rate.rating inside wineSchema.rates..
How can I do it?
So I have a Mongoose query question that I can't seem to figure out. I'm trying to query a schema to find all documents in the collection that have a parameter specified user id in one of a few places... What I have so far is this:
Schema:
var Module = new Schema({
template: { type: Schema.ObjectId, ref: 'template' },
owner: { type: String, required: true, index: { unique: false } },
primary: { type: Schema.ObjectId, ref: 'User' },
users: [{ type: Schema.ObjectId, ref: 'User' }],
data: [],
children: [{ type: Schema.ObjectId, ref: 'Module' }],
parent: { type: Schema.ObjectId, ref: 'Module' }
});
Query:
Module.find()
.or([{owner: req.user.id}, {primary: req.user.id}])
.populate('primary users children parent template')
.exec(function (err, modules) {
...
}
So as of now, it seems to correctly find documents that have the req.user.id as the primary or owner field, but how would I also return all documents where the users array is also searched for this value?
Thanks!
This question already has answers here:
Stop Mongoose from creating _id property for sub-document array items
(7 answers)
Closed 7 years ago.
I would like to add an element in an array in a mongo database:
db.keypairs.update( {pubkey: "1234567890"}, { $push: {listTxId: {txHash: "yyy", spent: false} } } )
The result is perfect:
listTxId" : [ { "txHash" : "xxx", "spent" : true },{ "txHash" : "yyy", "spent" : false } ]
Now I would like to do the same with node.js and mongoose
var res = wait.forMethod(Keypair,'update', {pubkey: "1234567890"}, { $push: { "listTxId": {"txHash":"zzz", "spent":false} } } );
Keypair is my node.js model for the mongoose collection:
var Keypair = require('./app/models/Keypair');
and wait.forMethod comes from a node module:
var wait = require('wait.for');
In the result, I have this "_id" element :
{ "txHash" : "zzz", "spent" : false, "_id" : ObjectId("56561571fea5d9a10a5771fd") }
QUESTION: where this ObjectId come from ? How can I get rid of it ?
UPDATE: mongoose schema:
var keypairSchema = mongoose.Schema({
userId : { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
pubkey : String,
privkeyWIF : String, // temp
balance : Number,
listTxId : [{
txHash : String,
spent : Boolean
}],
walletId : { type: mongoose.Schema.Types.ObjectId, ref: 'Wallet' },
description : { type: String, maxlength: 40 },
comments : String,
isMasterKey : { type: Boolean, default: false },
date : Date
});
Mongoose will put ids in your subdocument arrays. listTxId is a subdocument array. You can add _id: false to your schema to prevent this:
var keypairSchema = mongoose.Schema({
userId : { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
pubkey : String,
privkeyWIF : String, // temp
balance : Number,
listTxId : [{
_id: false,
txHash : String,
spent : Boolean
}],
walletId : { type: mongoose.Schema.Types.ObjectId, ref: 'Wallet' },
description : { type: String, maxlength: 40 },
comments : String,
isMasterKey : { type: Boolean, default: false },
date : Date
});