Why arrays of objects has ids on Mongoose? - node.js

I've went through some problems while saving some documents and realized that some inner documents has id references.
Let's take this schema for example:
var VisitSchema = mongoose.Schema({
user_id: { type: Schema.Types.ObjectId, ref: 'User' },
name: String,
city: {
name: String,
reference: String,
location: [Number]
},
photos: [{
image_url: String,
description: String
}]
});
When this schema is saved, here is the resulting document:
{
"_id" : ObjectId("5449eceeea5281056768aef8"),
"user_id" : ObjectId("540603dd797be100008b4340"),
"name" : "Test",
"photos" : [
{
"image_url" : "testURL",
"description" : "testDescription",
"_id" : ObjectId("5449eceeea5281056768aefb")
}
],
"city" : {
"name" : "New York, NY, United States",
"reference" : "CoQBdAAAAFfbZuaWptFtAkhGaO87UVSaXbyYwtTY_xX-pH84mS6QO2ypLr15znsCnYvaZ_N8CvwCBAr4y34PSQqyTUwxa5qbUKBK0yHnUFgTLKPQMFKqyQ8xd4vcDPNXf5XSxlpsXKKPYnU0AJZEVVxXLJ_6IBiUay9emFvNXPiYb7kT04NjEhB8fK-jKIZHJ5Bfz_mfyk2MGhTJwOPU68NQiV7RlAdb0Gca1bg0ew",
"location" : [
-74.0059413,
40.7127837
]
},
"__v" : 0
}
Why does the subdocument photos has an id reference? It doesn't make sense.
Thanks.

Related

How to specify and update an object within array in MongoDB

I'm trying to update the values of an object placed inside the array.
The MongoDB schema is as follows:
const ServiceStatus = new Schema({
CustomerName : { type : String},
CustomerNumber : {type : String},
ServiceName : {type : String},
Details : {type: String},
Date : {type: String},
Status : {type : String},
Comments : {type : String},
ServiceId : {type: Schema.Types.ObjectId},
CustomerId : {type: Schema.Types.ObjectId},
ServiceProvider : {type: Schema.Types.ObjectId},
message : [{
sender : {type: String},
content : {type : String},
time : {type : String}
}]
})
and the snippet of the route is
router.put('/message/customer/:id',(req, res) => {
const id=req.params.id;
Status.findByIdAndUpdate({_id : id},
{
$push : {
"message.$.sender": "Customer" ,
"message.$.content": req.body,
"message.$.date" : new Date()
}
}
,{ useFindAndModify: false } )
.exec((err, status) => res.json(status))
})
When I tried running it on postman it doesn't get updated but I don't get any error. I want to know how I should change the router to make it work.
I think it should be like this one:
db.ServiceStatus.insertOne(
{
CustomerName: "the name",
message: [{ sender: "Customer", content: "some content", time: new Date() }]
}
);
db.ServiceStatus.updateOne(
{ CustomerName: "the name" },
{
$push: {
message: { sender: "Another customer", content: "more content", time: new Date() }
}
}
)
db.ServiceStatus.find()
{
"_id" : ObjectId("5fdc4f14d1d3de1f92780a0b"),
"CustomerName" : "the name",
"message" : [
{
"sender" : "Customer",
"content" : "some content",
"time" : ISODate("2020-12-18T07:41:24.166+0100")
},
{
"sender" : "Another customer",
"content" : "more content",
"time" : ISODate("2020-12-18T07:41:26.328+0100")
}
]
}

Update Sub Sub Array item in MongoDB

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

How to update Reference Array in mongoose

I have a Group Collection, which is having a Reference array of Members. Two Objects are inter-connected like follow. When I am adding new members to the group the members field of Group object needed to be updated. How can I do this with a mongoose update operator.
var MemberSchema = new Schema({
name:{
type:String,
default:null
},
user_id:{
type : Schema.ObjectId,
ref : 'User',
default : null
}
});
var GroupSchema = new Schema({
name:{
type:String,
default:null
},
description:{
type:String,
default:null
},
members:[MemberSchema],
},{collection:"groups"});
Thank You in advance.
Update
I added a sample document of group.
{
"_id" : ObjectId("586a2e694467c41218b302c3"),
"members" : [
{
"_id" : ObjectId("586a2e694467c41218b302c6"),
"user_id" : ObjectId("58171d75e72bf516f92dcd4e"),
"name" : "Lakmal Kapukotuwa"
},
{
"_id" : ObjectId("586a2e694467c41218b302c5"),
"user_id" : ObjectId("5821807516325e127f59438e"),
"name" : "Prasad Perera"
},
{
"_id" : ObjectId("586a2e694467c41218b302c4"),
"user_id" : ObjectId("586263515356e908de6c899a"),
"name" : "Sadun Prasad"
}
],
"description" : "Des 1",
"name" : "My group",
"__v" : 0
}
If you are sending the new members as a list of objects with the following structure e.g.
membersListToAdd = [
{
"user_id": "58171d75e72bf516f92dcd4e",
"name": "foo"
},
{
"user_id": "5821807516325e127f59438e",
"name": "bar"
}
]
then use $push with $each modifier in an update as follows:
var query = { name: 'My Group' },
options = {},
callback = function (err, result) { console.log(result); };
Group.update(query, { $push: { members: { $each: membersListToAdd } } }, options, callback)
You are doing this wrong,
no need to have links in both collections and no need to nest models
try this instead
var Group = mongoose.model("Group", new Schema({
name: {
type:String
},
description: {
type:String
},
}));
Group.virtual("users", {
ref: "User",
localField: "_id",
foreignField: "groups"
});
var User = mongoose.model("User", new Schema({
name:{
type:String
},
groups: [{
type : Schema.ObjectId,
ref : 'Group'
}]
}));

Using aggregate with populate

I am trying to use aggregate with populate. I need $group to variable of referenced ObjectId Schema. The structure is like:
var jobFilter = mongoose.Schema({
location : { type: Schema.Types.ObjectId, ref: 'Location' },
field : {type: Schema.Types.ObjectId, ref: 'Jobfield'}
})
var locationSchema = mongoose.Schema({
city : String,
longitude : Number,
latitude : Number
});
and i want to group by _field and city. I wrote this query but it did not work because of city. Is it possible to populate Location somehow in this query?
jobFilter.aggregate(
[
{
$match : {
"jobFilter.field" : {$ne: null},
"jobFilter.location" : {$ne: null}}
},
{
$group :
{ _id: {
"field" : "$jobFilter.field" ,
"location" : "$jobFilter.location.city"
}, count: { $sum: 1}}},
{
$sort : { count : -1}
}
]
)
.exec()

Cannot update a property in an embedded Array in mongoose

I'm working on a commenting system with mongoose/n,
users can comment, and like in reddit, users should vote each comment up or down.
and i have the following comment scheme:
var commentSchema = new Schema({
text: String,
level: { type: Number, min: 0, max: 30, default: 0},
slug: String,
full_slug: String,
discussion_id: { type: Schema.ObjectId, ref: 'Uranus' },
parent_id: {type: Schema.ObjectId,ref: 'Comment'},
score: [{
upvote: {type: Number,min: 0,max: 9000},
downvote: {type: Number,min: 0,max: 9000},
voter: {type: Schema.ObjectId,ref: 'Account'}
}],
updated: { type: Date, default: Date.now },
created: { type: Date, default: Date.now },
author: { type: Schema.ObjectId, ref: 'Account' },
});
it works just fine, but i have no clue, how to update the score-array. it just doesn't work.
Here is the sample json-data i got:
{
"__v" : 0,
"_id" : ObjectId("52a0d4ff779edff16d000006"),
"author" : ObjectId("529dfdda6b2d7a450c000009"),
"created" : ISODate("2013-12-05T19:33:19.229Z"),
"discussion_id" : ObjectId("529f7b04cbab31cc3e000004"),
"full_slug" : "2013.12.05.19.33.19:e1CDx79g8",
"level" : 0,
"score" : [
{
"upvote" : 1,
"downvote" : 0,
"voter" : ObjectId("529dfdda6b2d7a450c000009"),
"_id" : ObjectId("52a0d4ff779edff16d000007")
},
{
"upvote" : 0,
"downvote" : 1,
"voter" : ObjectId("52a0d9883027a89d6e000002"),
"_id" : ObjectId("52a0d9903027a89d6e000004")
},
{
"upvote" : 0,
"downvote" : 1,
"voter" : ObjectId("52a0d99a3027a89d6e000005"),
"_id" : ObjectId("52a0d9a63027a89d6e000007")
}
],
"slug" : "e1CDx79g8",
"text" : "A Comment",
"updated" : ISODate("2013-12-05T19:33:19.229Z")
}
so, i just update the comment by
var query = {
'score.voter': mongoose.Types.ObjectId(String('52a0d9883027a89d6e000002'))
};
Comment.update( query, {$set: {"score.$.upvote": 10}} )
The problem is, that it's just not updating.
i know, there are a few other questions regarding this problem, but all solutions are not working for me. i hope someone can help me.
UPDATE:
Found the problem, Seems like you have to have a callback on the update function like this:
Comment.update( query, {$set: {"score.$.upvote": 10}}, { multi: false }, function(err,n){
console.log("affected rows:", n)
});

Resources