Trying to $pull from the variable key in mongoose - node.js

UserEventsDetails.findOneAndUpdate({"username": username},
{$pull: { req.query.eventtype : { "name": req.query.eventname } }
},
{safe: true, upsert: true, new: true},
function(err, model){
if (err){
console.log("ERROR: ", err);
res.send(500, err);
}else{
res.status(200).send(model);
}
}
);
I am using this to pull from the mongodb. But can't use req.query.evenrname

Create the update document first using the square bracket notation or if using ECMAScript 6 computed values with object literals to initialize properties from variables:
var update = {};
update[req.query.eventtype] = { "name": req.query.eventname };
// or with ES6
let update = {
[req.query.eventtype]: { "name": req.query.eventname }
}
Then use the above object in your update statement:
UserEventsDetails.findOneAndUpdate(
{ "username": username },
{ "$pull": update },
{ "upsert": true, "new": true},
function(err, model){
if (err){
console.log("ERROR: ", err);
res.send(500, err);
}else{
res.status(200).send(model);
}
}
);

Related

Mongoose - replace all array elements

I want to replace all array's elements in 'prices' filed as below:
{
"name": "My customer name"
"taxCode":123456
"prices":
[
{
"name": "Chocolate",
"unitPrice": 10
},
{
"name": "Cookie",
"unitPrice": 9
}
]
}
The JSON that uses to change 'prices' is:
{
"prices":
[
{
"name": "Chocolate1",
"unitPrice": 10
},
{
"name": "Candy",
"unitPrice": 5
}
]
}
And here is my code to replace the 'prices' array
router.route('/:obj/:id')
.put((req, res) => {
const PObj = require('../models/customer');
PObj.findById(req.params.id, (err, doc) => {
if (err) {
console.log('Lookup error: ' + err);
res.status(500).send('Error');
} else if (doc) {
doc.update({$set: req.body}, (err, task) => {
res.status(200).json(task);
}); } else {
res.status(404).send('Something is wrong');
}
});
});
After code executed is done but without any changes in Mongo DB. Please help me to correct my code. Thank!
If your req.body prints that prices array then it has to be req.body.prices, also rather than fetching the document & updating it - Which is a two- way process, You can try this :
router.route("/:obj/:id").put((req, res) => {
const PObj = require("../models/customer");
PObj.findByIdAndUpdate(
req.params.id, /** this 'req.params.id' has to be `_id` value of doc in string format */
/** internally mongoose will send this as { $set: { prices: req.body.prices }} which will replace `prices` array will new array,
* Just in case if you wanted to push new values, have to manually do { $push: { prices: req.body.prices }} each object */
{ prices: req.body.prices },
{ new: true }, /** returns updated doc, this option is not needed if you don't need doc - by default it returns old doc */
(err, doc) => {
if (err) {
console.log("Lookup error: " + err);
res.status(500).send("Error");
} else if (doc) {
res.status(200).json(task);
} else { /** `doc` value will be null if no doc is not found for given id */
res.status(404).send("Something is wrong");
}
}
);
});
Ref : .findByIdAndUpdate()

How to $set new Date() in MongoDB?

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

Update array in mongoDB through my loopback application

I am developing API using loopback + mongoDB. In that i have to update an array in a document in mongoDB:
My model:
{
"userId": "546fgdfgd445",
"rrrr": "7",
"bbbbb": [
{}
],
"id": "57a437789521b58b12124016"
}
I need to update the array with new element with the data sent form client:
app.models.vvvvv.update({ userId: '546fgdfgd445' },{ $push: { "transactions": transactionData }}, function(err, res){
if(err){
console.log(err);
} else {
console.log(res);
}
});
But i am receiving error:
{ name: 'MongoError',
message: 'The dollar ($) prefixed field \'$push\' in \'$push\' is not valid for storage.',
driver: true,
index: 0,
code: 52,
errmsg: 'The dollar ($) prefixed field \'$push\' in \'$push\' is not valid for storage.' }
I am using mongoDb version 3.2.3.
Please share your ideas. Thanks in advance.
in model.json you need to enable extended operations like this :
"options": {
"mongodb": {
"collection": "model_collection",
"allowExtendedOperators": true
}
},
or
app.models.vvvvv.update({ userId: '546fgdfgd445' },
{ $push: { "transactions": transactionData }}, { allowExtendedOperators: true }, function(err, res){
if(err){
console.log(err);
} else {
console.log(res);
}
});

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");
}
);

MongoClient Native FindAndModify "Need update or remove" Error

My node.js client looks like this:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect(mongoendpoint, function(err, db) {
if(err) throw err;
var collection = db.collection('test-collection');
var ws = new WebSocket(websocket_Endpoint);
ws.on('open', function() {
log.info('Connected.');
});
ws.on('message', function(data, flags) {
wsevent = JSON.parse(data);
var args = {
'query': {
id: '1.2.3.4'
},
'update': {
$set: {
lastseen: "201405231344"
},
$addToSet: {
record: "event123"
}
},
'new': true,
'upsert': true
};
collection.findAndModify(args, function(err, doc){
log.info(err);
});
});
});
When I run this, I get the following error:
info: name=MongoError, ok=0, errmsg=need remove or update
I can't figure out why. I can run the exact same args json above using RoboMongo and the query works just fine.
Robomongo Query
db['test-collection'].findAndModify({"query":{"id":"1.2.3.4"},"update":{"$setOnInsert":{"lastseen":"201405231344"},"$addToSet":{"record":"event123"}},"new":true,"upsert":true});
What am I missing?
Your args section is wrong, it should be an array and does not need key values for "query" and "update". And the "options" value also needs to be an object (sub-document):
var args = [
{ id: '1.2.3.4' },
{
$set: {
lastseen: "201405231344"
},
$addToSet: {
record: "event123"
}
},
{
'new': true,
'upsert': true
}
];
Or specifically in the call:
collection.findAndModify(
{ id: '1.2.3.4' },
{
$set: { lastseen: "201405231344" },
$addToSet: { record: "event123" }
},
{
'new': true,
'upsert': false
},
function(err, doc){
Examples are also included on the manual page.

Resources