How to $set new Date() in MongoDB? - node.js

I have tried quite a few combinations and checked the MongoDB 3.2 docs, but I still am not getting my new Date() stored in my DB. Everything else below is getting properly stored. Thanks in advance for any tips!
Code from my app.js file:
db.collection('users').update({user: req.user.username}, {
$push: {
"recentPlays": {
"quiz": req.session.mostRecentQuiz,
"score": score
}
}
},{
$set: {
"mostRecentQuiz.quizObj": req.session.mostRecentQuiz,
"mostRecentQuiz.time" : new Date() // StackOverflow: this is the part that is not getting stored in the DB.
}
}, function (err, result) {
if (err) throw err;
console.log(result);
});

Your update method is being called the wrong way, the update operators $set and $push should be in the same document. Re-write your method as:
db.collection('users').update(
{ "user": req.user.username },
{
"$push": {
"recentPlays": {
"quiz": req.session.mostRecentQuiz,
"score": score
}
}
"$set": {
"mostRecentQuiz.quizObj": req.session.mostRecentQuiz,
"mostRecentQuiz.time" : new Date()
}
}, function (err, result) {
if (err) throw err;
console.log(result);
}
);

Related

mongodb using $not getting undefined, in NodeJs

I am trying to make a find command in Mongo using $not as i see in this link,
await Match.find(
{
type:"Friendly", status:"Pending", "date.fullDate":{$gt: date},
$not:{$or: [{"team1.players":{$elemMatch: {_id:playerId}}}, {"team2.players":{$elemMatch: {_id:playerId}}}]}
}).sort({'date.fullDate':1}).exec(function(err, doc) {
console.log(doc)
return res.send({data: doc});
});
However, i am getting undefined.
I am thinking the problem is with the $not because when i remove it and make the command like this it works.
await Match.find(
{
type:"Friendly", status:"Pending", "date.fullDate":{$gt: date},
$or: [{"team1.players":{$elemMatch: {_id:playerId}}}, {"team2.players":{$elemMatch: {_id:playerId}}}]
}).sort({'date.fullDate':1}).exec(function(err, doc) {
console.log(doc)
return res.send({data: doc});
});
Note: that team2 could be null in the documents.
Any ideas why i am getting this undefined.
My document look like this:
match:{
team1:{
players:[
_id:value,
otherfields...
]
},
team2:{
players:[
_id:value,
otherfields...
]
}
}
await Match.find({
type: "Friendly", status: "Pending", "date.fullDate": { $gt: date },
$or: [
{
$not: {
"team1.players": { $elemMatch: { _id: playerId } }
}
},
{
$not: {
"team2.players": { $elemMatch: { _id: playerId } }
}
}
]
}).sort({ 'date.fullDate': 1 }).exec(function (err, doc) {
console.log(doc)
return res.send({ data: doc });
});
I had to use $nor instead of $not:{$or:[]}
Similar question here.

How to update a array value in Mongoose

I want to update a array value but i am not sure about the proper method to do it ,so for i tried following method but didnt worked for me.
My model,
The children field in my model
childrens: {
type: Array,
default: ''
}
My query,
Employeehierarchy.update({ _id: employeeparent._id} ,{ $set: {"$push": { "childrens": employee._id }} })
.exec(function (err, managerparent) {});
Can anyone please provide me help.Thanks.
You can't use both $set and $push in the same update expression as nested operators.
The correct syntax for using the update operators follows:
{
<operator1>: { <field1>: <value1>, ... },
<operator2>: { <field2>: <value2>, ... },
...
}
where <operator1>, <operator2> can be from any of the update operators list specified here.
For adding a new element to the array, a single $push operator will suffice e.g. you can use the findByIdAndUpdate update method to return the modified document as
Employeehierarchy.findByIdAndUpdate(employeeparent._id,
{ "$push": { "childrens": employee._id } },
{ "new": true, "upsert": true },
function (err, managerparent) {
if (err) throw err;
console.log(managerparent);
}
);
Using your original update() method, the syntax is
Employeehierarchy.update(
{ "_id": employeeparent._id},
{ "$push": { "childrens": employee._id } },
function (err, raw) {
if (err) return handleError(err);
console.log('The raw response from Mongo was ', raw);
}
);
in which the callback function receives the arguments (err, raw) where
err is the error if any occurred
raw is the full response from Mongo
Since you want to check the modified document, I'd suggest you use the findByIdAndUpdate function since the update() method won't give you the modified document, just the full write result from mongo.
If you want to update a field in the document and add an element to an array at the same time then you can do
Employeehierarchy.findByIdAndUpdate(employeeparent._id,
{
"$set": { "name": "foo" },
"$push": { "childrens": employee._id }
}
{ "new": true, "upsert": true },
function (err, managerparent) {
if (err) throw err;
console.log(managerparent);
}
);
The above will update the name field to "foo" and add the employee id to the childrens array.
can follow this
if childrens contains string values then model can be like:
childrens: [{
type : String
}]
if childrens contains ObjectId values of another collection _id and want populate then model can be like:
childrens: [{
type : mongoose.Schema.Types.ObjectId,
ref: 'refModelName'
}]
no need to use $set just use $push to insert value in childrens array. so query can be like:
Employeehierarchy.update(
{ _id: employeeparent._id},
{"$push": { "childrens": employee._id } }
).exec(function (err, managerparent) {
//
});
This will help I guess
Employeehierarchy.findOneAndUpdate(
{ _id:employeeparent._id },
{ $set: { "childrens": employee._id }}
)

How do i $set and $push in one update MongoDB?

I'm trying to $push and $set at the same time, $push is working just fine, when it comes to $set, it generates this error:
MongoError: The positional operator did not find the match needed from
the query. Unexpanded update: files.$.name
Here's the code
Course.update(
{
_id: req.body.courseId,
'files.fileUrl': { $ne: url }
},{
$push: { files: { fileUrl: url } },
$set: {'files.$.name': file.name},
}, function(err, count) {
if (err) return next(err);
console.log("Successfully saved")
});
and the ORM model, I'm using mongoose
var CourseSchema = new Schema({
files: [{
fileUrl: String,
name: { type: String, default: 'File name'}
}]
});
Any help would be appreciated. Thanks.
As the error states looks like the query used is returning no documents or returning documents having no files[].
Another reason for which it might be throwing error is that you're trying to $push & $set in the same field files and probably running into an issue similar to https://jira.mongodb.org/browse/SERVER-1050
IMHO, there is no good reason to use the same field in $push & $set, instead you can simply change
$push: { files: { fileUrl: url } },
$set: {'files.$.name': file.name},
to
$push: { files: { fileUrl: url, name: file.name } },
I have written similar kind of query for my project
Hope u could relative this to your scenario
exports.candidateRating = function(req, res) {
console.log(req.query);
console.log(req.body.RoundWiseRatings);
Profiles.update({
"name": req.query.name
}, {
$set: {
"ratings": req.body.ratings,
},
$push: {
"RoundWiseRatings": req.body.RoundWiseRatings
}
}, {
multi: true
}, function(error, profiles) {
if (error) {
}
return Profiles.find({
name: req.query.name
}, function(err, profiless) {
console.log(profiless);
if (err) {
return handleError(res, err);
}
return res.status(200).json(fnStruncturedData(profiless[0].RoundWiseRatings));
});
});};
And this worked for me :)

Mongoose findOneAndUpdate Updating Multiple Fields

The findOneAndUpdate method doesn't work properly. I'm trying to update all the fields all at once but it's only updating (setting) the last field. It's always only the last field. Can someone tell me what I'm doing wrong or what can I do to have the expected effect?
This is my findOneAndUpdate code:
Book.findOneAndUpdate({_id:bookId},{$set:{"name": name},$set:{"genre": genre},$set:{"author": author},$set:{"similar": similar}}).exec(function(err, book){
if(err){
console.log(err);
res.status(500).send(err);
} else {
res.status(200).send(book);
}
});
You are using the $set operator multiple times. The correct syntax for $set is :
{ $set: { <field1>: <value1>, ... } }
You need to change your update argument like this:
Book.findOneAndUpdate({ "_id": bookId }, { "$set": { "name": name, "genre": genre, "author": author, "similar": similar}}).exec(function(err, book){
if(err) {
console.log(err);
res.status(500).send(err);
} else {
res.status(200).send(book);
}
});

How to handle error when MongoDB collection is updating in JavaScript(Node.js)

I've been trying get an error when running bad code. The following code tries to update a record which has _id value 5. There is actually no such record, but I can't catch any error messages with the following function.
What should I do?
collection.update(
{ _id : "5" },
// { _id : req.session.User._id },
{ $set: { password : req.param('password') } },
{ writeConcern: { w: "majority", wtimeout: 3000 } },
function(err, result) {
if (err) { console.log(err); return err; }
res.send("/user/show");
}
);
The callback of update() has 2 arguments, err and result. When the item is updated, result is set to true, false otherwise. So when the item is not updated because item is not found, it's not considered an error, so err is null. if (err) won't be true. You need to test for updated this way:
collection.update(
{ _id : "5" },
// { _id : req.session.User._id },
{ $set: { password : req.param('password') } },
{ writeConcern: { w: "majority", wtimeout: 3000 } },
function(err, result) {
if (err) { console.log(err); res.send(err); return;}
if (result) {
res.send("/user/show");
} else {
res.send("/user/notshow");
}
);

Resources