how to update data in mongodb using angular nodejs express - angularjs

I want to update the likes' value with 1.
My MongoDB structure is as follows .
{"_id":{"$oid":"5f980a66c4b0d52950bdf907"},
"course_id":"5002",
"lecture_id":"451",
"__v":0,
"created_at":{"$date":"2020-10-27T11:54:14.842Z"},
"message":[
{
"_id":{"$oid":"5f980a84c4b0d52950bdf90a"},
"from":{
"userId":"68819","name":"Developer IIRS",
"avatar":"https://api.adorable.io/avatars/285/811753.png"
},
"content":"ok",
"likes":0,
"parent_id":null,
"created_at":{"$date":"2020-10-27T11:54:44.388Z"}
}
]
}
Here is my code to update value of likes
router.post('/:lectureId/:courseId/:id', function(req, res, next) {
let query = {
lecture_id: req.params.lectureId,
course_id: req.params.courseId
};
let update = { $push: { message: { _id: req.params.id,likes: 1 } } }
var options = {
new: true
}
console.log('Liked', query)
Chat.update(query, update, function(err, result) {
if (err) {
//res.send(err);
console.log('err',err );
return err;
}
res.json(result);
})
});
Its basically adding new document. I am stuck here how can i do this.

"lecture_id": "451",
"course_id": "5002"
},
{
$inc: {
"message.$[elem].likes": 1
}
},
{
new: true,
arrayFilters: [
{
"elem._id": "5f980a84c4b0d52950bdf90a"
}
]
})```

Here is the mongo query.
db.collection.update({
"lecture_id": "451",
"course_id": "5002",
"message._id": "5f980a84c4b0d52950bdf91a"
},
{
"$inc": {
"message.$.likes": 1
}
})
Try it here Mongo Playground
Not an expert in nodejs. Below update statement may work for you.
let update = { $inc: { "message.$.likes": 1 } }

Related

mongodb sending userid's in an array as a query and return the json object of the users present in collection

I have a collection of online users here goes its model
var SessionDetailSchema = mongoose.Schema({
providerID: {
type: String
},
firstName: {
type: String
},
email: {
type: String
},
status: {
type: String
}
},{ timestamps: true });
var sessionDetail = module.exports = mongoose.model('OnlineUser', SessionDetailSchema);
I am trying to send an array of providerID's so that I wanted to check the collection which all providerId's are present and return me those providerID details.
and this is what I tried
router.post('/sessiondetails:find', function (req, res, next) {
console.log(req.body.providerID)
sessionDetail.find({ "providerID": { $in: req.body.providerID} }, function (err, users) {
if (users) {
console.log(users)
} else {
console.log("not there")
}
})
})
unfortunately, I am getting the only first providerid response for multiple times.
i am sending the array from the postman it looks like this
{
"providerID":["1090867867720278", "104761648907225164100", "114316680403119099502", "103668441331122956874"]
}
can some help me? thanks in advance.

how to push element into array inside array in mongodb while updating the sibling field of parent array in document

Hell devs, Here is my document schema
var Schema = mongoose.Schema;
var botSchema = new Schema({
Bot_name: String,
UserName:String,
Modules: [{
ModuleStatement: String,
ModuleID: String,
ModuleResponse: [{
Response: String,
TransBotID: String
}]
}]
});
what i want to do is update the ModuleStatement as well as push the element into ModuleResponse setting Response and TransBotID to some values
I tried following but it only updates the ModuleStatement and doesn't push element into ModuleResponse
botSchema.update({ 'Modules.ModuleID': req.body.ModId }, { '$set': { 'Modules.$.ModuleStatement': req.body.Statement } }, function (err, data) {
if (err) {
throw err;
} else {
botSchema.update({ "Modules.ModuleID": req.body.ModId }, { "$push": { "ModuleResponse": { "Response": req.body.Statement, "TransBotID": req.body.transitmod } } }, function (err, data) {
if (err) {
throw err;
}
else {
res.json('upgraded');
}
})
}
})
how can i push element into ModuleResponse while setting the ModuleStatement at the same time?
$push is only available in the $group stage. You may want to try as the following:
botSchema.find({'Modules.ModuleID': req.body.ModId}, (err, bots) => {
if (err) {
throw err;
} else {
bots.forEach((bot) => {
bot.modules.forEach((botModule) => {
if (botModule.ModuleID == req.body.ModId) {
botModule.Statement = req.body.Statement;
botModule.ModuleResponse.push({
Response: req.body.Statement,
TransBotID: req.body.transitmod
})
}
});
bot.save((err, data) => {
if (err) throw err;
});
});
res.json('upgraded');
}
})
Here you have a shell code:
db.bot.update(
{ "Modules.ModuleID": "<some_id>" },
{
"$set": { "Modules.$.ModuleStatement": "<some_statement>" },
"$push": {
"Modules.$.ModuleResponse": {
"Response" : "<some_response>",
"TransBotID" : "<some_trans_id>"
}
}
}
)
The thing is that you can have more than one update expressions in one update document. I believe you can convert it to mongoose quite easily.

update all values in the sub array of one object in mongodb using mongoose

user = {
'userid':'111',
'mail':[{
'time':22222,
'info':'this is a info1',
'read':false,
},{
'time':33333,
'info':'this is a info2',
'read':false,
}]
}
then, I want to change one user's read flag to true, how can i do for it ?
here is my answer:
User.update({
'userid':userid,
'mails':{
'$elemMatch':{
'read':false
}
}
},{
'$set':{
'mail.$.read':false,
'newmail':0,
}
}, { multi: true }, function (err, data) {
if(err > 0){
console.log('ReadMail err', err);
}
});
here is a simple example: my model is User !! my url is the path to the DB
var newUser = new User();
newUser.name = request.body.name;
newUser.email = request.body.email;
newUser.pass = request.body.pass;
newUser.position = request.body.pos;
newUser.phone = request.body.phone;
mongoose.connection.openUri(url);
var myquery = { _id : request.params._id };
console.log("updating...")
User.findByIdAndUpdate(myquery,{$set: newUser},{new: true},function(err, result) {
if(err)
{
throw err;
}
response.json({code: 0 , result});
});

How to write an if statement to check whether any item in array is greater than a specific value/date?

So, I have a function which should be executed in case that a if condition is true. I simply do not know how to implement it in a method. I have the following code:
Meteor.methods({
'popItems': function () {
var date = new Date().getTime();
if ( "check if this.userId && any item in the array 'itemIds' is $gt date" ) {
userManagement.update({
'_id': this.userId
}, {
$pop: {'itemIds': -1}
}
}
);
};
}
});
So, in case the if condition is true, the $pop function should be executed. In case false, it should not. I wrote this for the if clause, but it doesn't work:
if (this.userId && userManagement.find({
'itemIds': {$gt: date}})) {...$pop function...}
Meteor.methods({
'popItems': function () {
var date = new Date().getTime();
if (this.userId && userManagement.find({'itemIds':{ $gt: date}}).count() > 0 ) {
userManagement.update({
'_id': this.userId
}, {
$pop: {'itemIds': -1}
});
}
};
});
Include the query in the update operation as
Meteor.methods({
'popItems': function () {
var date = new Date();
userManagement.update(
{
'_id': this.userId,
'itemIds': { '$gt': date }
},
{ '$pop': { 'itemIds': -1 } }
);
}
});
I've made some assumptions in coming up with the above solution. The first one being itemIds is an array composed of just Date objects e.g.
itemIds: [
ISODate("2017-01-25T06:20:00.000Z"),
ISODate("2017-01-26T06:20:00.000Z"),
ISODate("2017-01-27T06:20:00.000Z"),
...
ISODate("2017-02-25T06:20:00.000Z")
]
The above query in the update operation can also be specified with an $and operator as:
Meteor.methods({
'popItems': function () {
var date = new Date();
userManagement.update(
{
'$and': [
{ '_id': this.userId },
{ 'itemIds': { '$gt': date } },
]
},
{ '$pop': { 'itemIds': -1 } }
);
}
});

MongoDB: how can I find and merge array

I'm trying to find a specific ID in my document and then merge an array to the existing one, for example if I have this array stored in db.friends:
["12","13","14"]
and I send this array: ["12","16","18"], db.friends should contain: ["12","13","14","16","18"]
I'm using underscore library, but I'm not sure I have to (maybe "aggregate" in mongoose?)
Here is what I did, can you tell me where am I wrong?
function saveFollowers(req, res) {
var friends = req.body.friends; // the new array to merge ["54aafe9df4ee360300fc94c7"];
User.findOne({_id: req.user._id}).exec(function (err, user) {
if (err) {
res.jsonp({error: "Error fetching user info"})
} else {
friends = _.extend(friends, user.friends); //user.friends=existing friends we have in db
user.save(function (err) {
if (err) { res.jsonp({error: "Cant save"}); }
console.log("Friends NOW:"+JSON.stringify(friends)); //Here I don't see the merge, also, I can't see it in mongo db.
res.jsonp("success");
});
}
});
Thank you!
With your current implementation, you haven't actually modified the friends key in the returned user object. So rather you can use the union method as
user.friends = _.union(friends, user.friends); //user.friends=existing friends
user.save(function (err) { .. }
Or with ES6 using the spread operator for concatenating the array and Set for creating a distinct set of elements:
user.friends = [...new Set([...friends ,...user.friends])];
user.save(function (err) { .. }
Another alternative is using the aggregation framework, you could utilize the $setUnion operator:
function saveFollowers(req, res) {
var friends = req.body.friends; // the new array to merge ["54aafe9df4ee360300fc94c7"];
User.aggregate([
{ "$match": { _id: req.user._id } },
{
"$project": {
"friends": { "$setUnion": [ "$friends", friends ] }
}
}
]).exec(function (err, results){
if (err) {
res.jsonp({error: "Error fetching user info"})
} else {
User.findByIdAndUpdate(req.user._id,
{ "$set": { "friends": results[0].friends } },
{ "new": true },
function (err, user) {
if (err) { res.jsonp({error: "Cant save"}); }
console.log("Friends NOW: "+ JSON.stringify(user.friends));
res.jsonp("success");
}
);
}
});
}

Resources