push array in array field in mongodb [duplicate] - node.js

This question already has answers here:
Push items into mongo array via mongoose
(11 answers)
Closed 4 years ago.
I have an array called students in a schema called Course. I created a route that allows me to add students to this array using a student's ObjectID like so:
router.put('/addStudent/:courseID', function (req, res) {
Course.findOneAndUpdate({courseID: req.params.courseID}, {$push: {students: req.body.students}})
.populate('students')
.exec(function (err, course) {
if (err) return res.status(500).send("There was a problem adding this information to the database");
res.status(201).send(course);
})
});
When I try making a PUT request to my endpoint with the following JSON body:
{
"students":["5b1f06cafa355c2d187c344f"]
}
Nothing happens at all, it just sends me back the course with the student ID not added. How do I make it so I could add more student IDs to the array? I don't want it to replace the array with a student ID, I want to keep adding more as I make more requests.
Thanks!

You need to use $each with $push
Course.findOneAndUpdate(
{ courseID: req.params.courseID },
{ $push: { students: { $each: req.body.students } } }
)
Course.findOneAndUpdate(
{ courseID: req.params.courseID },
{ $addToSet: { students: { $each: req.body.students } } }
)

put request will update your db and findOneAndUpdate method from mongoose is also for updating you current item, you need to use post request and save method in mongoose instead if you want create a new item.

You can Try this:
Course.findOneAndUpdate(
{ courseID: req.params.courseID },
{ $push: {
students: req.body.students
}}, options, function(err, values){
});

Related

How to reuse already exec query mongodb mongoose in nodejs

is that posible to reuse already exec mongodb/mongoose query in nodejs?
for example i create query like this to check if user exist or not:
const inviter = await User.findOne({ _id: req.userData._id }).exec()
// there's bunch of code bellow here before update the user data
basically if i want to update the data, then i have to write the same code again and add update function like this:
User.findOneAndUpdate({ _id: req.userData._id }, { $push: { invited: recipient.value } }, { useFindAndModify: false })
is that posible to continue the first query and add short query to update based on result of the first query, for example like this:
inviter.update({ $push: { invited: recipient.value }).exec()
i know this code is not work..
you can use this approach :
User.findOne({ _id: req.userData._id }).exec((err, result) => {
if(result)
{
result.invited = recipient.value;
result.save((err) => {
if (err) // do something
});
}
})
}

findByIdAndUpdate does not work in express, but does work in mongo tool [duplicate]

This question already has answers here:
Mongoose: findOneAndUpdate doesn't return updated document
(16 answers)
How to push an array of objects into an array in mongoose with one call?
(4 answers)
Push to two separate arrays in one update call in mongodb
(1 answer)
Closed 4 years ago.
I am a beginner of mongodb and express, now I am trying to update some data. I do not think there is something wrong in my code, when I turn debugging on, the following db operation is printed out and does not return any error from catch, therefore without any doubt, I thought the following update is executed without fail. Even I tested with the following update statement directly from mongo client tool, it worked fine. However it is not reflected on the actual database if I update from express. If updating is not successful, it should return some error, but it does not. Could you anyone give me some advice for this? I really do not know what is happening here, the following db operation works well from the mongo client tool. From express, it does not return error also. So, I come to ask about this.
Mongoose: persons.findOneAndUpdate({ _id: ObjectId("5be6d1087594078eac687f19") }, { '$push': { hobbies: { '$each': [ 'TEST', 'SING', 'SWIM' ] } } }, { '$push': { skills: [ 'programming' ] }, upsert: false, projection: {}, returnOriginal: true })
router.post("/edit/:id", (req, res, next) => {
var hobbies = req.body.hobbies.split(",");
var skills = req.body.skills.split(",");
Person.findByIdAndUpdate(
req.params.id,
// { $set: { name: req.body.name } }
{ $push: { hobbies: hobbies} },
{ $push: { skills: skills} }
)
.exec()
.then(person=> {
res.json(person);
})
.catch(err => {
console.log("ERROR", err);
});
});

How to update a specific value in object of MongoDb via Post?

I have a schema with sub objects, i want to be able to update a specific key inside of it. If i update only a specific key - like in the Post example - it's empty all the other keys..
for example :
{
"_id": "32323323",
"names":{
"firstname":"John",
"lastname":"foo",
"workers":{
"position":"manager",
"address":"1 st"
}
}
}
I want to update Only "position" key via Post request , for example :
$.post({
url: 'workers/information/',
data: {
user_id: user_id,
names: {
workers: {
position: some data,
}
}
},
success: function (result) {
alert('Your information updated successfully')
}
});
Here is the update method in NodeJs server :
UserDataController.updateWorkersInformation = function (userID, workersInformation, cb) {
if (userID) {
user.findOneAndUpdate({_id: userID}, workersInformation, function (err, result) {
if (err) return cb(err);
return cb(null, result);
});
}
};
You may want to look into mongoose. It provides a more simple interface than the native client does.
https://www.npmjs.com/package/mongoose
However, as the comment mentioned, you are missing the $set operator. {$set:workersInformation}
If update is called without the $set operator, the entire document will be replaced with your update object.
http://mongodb.github.io/node-mongodb-native/2.2/tutorials/crud/

Issue in saving values in array in mongoose model using save() [duplicate]

This question already has answers here:
Push items into mongo array via mongoose
(11 answers)
Closed 5 years ago.
I am trying to update a document in a collection. I am particularly trying to update an array of Strings.The following is my Schema
var sampleSchema= mongoose.Schema({
fullName : String,
email : String,
rolesTaken : [String],
});
I basically have an array of such schema's. I want to update the rolesTaken array for all of them.
So I did the following
var async = require('async');
var ATmapping = require('path to Schema');
ATmapping.find({},function(err,lists){
if(err){
console.log(err);
return;
}
if(lists.length > 0){
async.each(lists,function(list,callback){
if(!list.rolesTaken){
list.rolesTaken =[];
}
list.rolesTaken.push("Patient");
list.markModified('rolesTaken');
list.save(function(err,item){
if (err){
console.log(err);
}
console.log('Saved', item);
callback();
});
});
}
});
I have browsed a lot and the most popular solution was to add markModified. But it doesn't seem to work in my case.When I added mongoose.debug i got the following
atmappings.update({ _id: ObjectId("59074b127adeef0004b84ac3"), __v: 7 }, { '$set': { rolesTaken: [] }, '$inc': { __v: 1 } })
As you can see the roles taken is empty despite me adding markmodified and save(). I would like to know if I am missing something which is preventing me from saving the values in the schema.
Thanks in advance.
Here is how I push a comment to a thread in one of my apps using mongoose.
Thread.findByIdAndUpdate(body.thread, { $push: { comments: comment.id }})
I simply find the thread by the id, then use the $push operator to push the comment id to the comments attribute where I populate later.
You can read more into the $push operator here (mongoose v3.4) https://docs.mongodb.com/manual/reference/operator/update/push/

Selecting only modified subdocument from Mongo

I have a mongoose query like this:
var query = Events.findOneAndUpdate({ '_id': event._id,'participants._id':participant._id},{'$set': {'participants.$': participant}}, {upsert:false,new: true},function(err,result){
if(err){
return res.status(500).jsonp({
error: 'Unable to update participant'
});
}
console.log(result.participants[0]);
res.jsonp(result.participants[0]);
});
and the query works properly modifying the participants subdocument inside Events collection.
The problem:
I need only the modified participant to be returned as JSON and I am not in need of the entire participants array but I am not able to achieve this since I get all the participants when I do console.log(result.participants);
How do I get only the modified subdocument after the query?
You may have to use the native JS filter() method as in the following:
Events.findOneAndUpdate(
{ '_id': event._id, 'participants._id': participant._id },
{ '$set': { 'participants.$': participant } },
{ upsert: false, new: true },
function(err, result){
if(err){
return res.status(500).jsonp({
error: 'Unable to update participant'
});
}
var modified = result.participants.filter(function(p){
return p._id === participant._id
})[0];
console.log(modified);
res.jsonp(modified);
}
);

Resources