Concatanate Variable And Query MongoDB - node.js

This is my working query:
collection.update({ _id: '124'}, {$addToSet: {'data.dropdowns.accessRoles': req.body.newItem}}, function(err, results) {
//
});
I want to change data.dropdowns.accessRoles according to input string. Input variable is stored in req.body.listName. I tried this, but it didn't work:
{$addToSet: {'data.dropdowns.req.body.listName': req.body.newItem}}
Any ideas?

Assembly your $addToSet object programmatically:
var addToSet = {};
addToSet['data.dropdowns.' + req.body.listName] = req.body.newItem;
collection.update({ _id: '124'}, {$addToSet: addToSet}, function(err) {...});

Related

Update many records by id

i'm woking with mongoose on a project and i have the following issue:
I need to update many records by its ids ( these ids was stored in an array ), i've tried this method:
Collection.update({$in:{"_id":ids}}, {$set:{data_of_id}}, {upsert : true},
{"multi": true}, function(err, res){
if(err){ console.log(err) };
console.log(res);
});
ids[] is the ids of the collection i need to update, and data_of_id is the new records wich will replace the old records. But i don't know how to associate these ids with each record in the array. I tried to put the update query into a foreach method too, but no success. The query above don't return any error or message, the called method was executed but don't execute the query.
The $in syntax is incorrect, it should be:
{ field: { $in: [<value1>, <value2>, ... <valueN> ] } }
So, you should write it like this:
Collection.update({_id: {$in: ids}}, ...);
I've solved doing by this way:
datas.forEach(function(data){
Collection.update({"_id":data._id},
data, {upsert : true},{new : true}, function(err, res){
if(err) console.log(err);
});
});

Mongoose OR operator with _id

I'm using mongoose.
When I do this, it works fine:
userModel.find({ $or:[
{first_name:"Bob"},
{last_name: "Marley"}
]
}, function(err, result){
if(err) //do something;
console.log(result);
});
But when I use _id as one of the expressions, it only looks for the _id and doesn't care about the other expressions:
userModel.find({ $or:[
{_id: "56b426aa1d6c7a642ab1a52d"},
{last_name: "Marley"}
]
}, function(err, result){
if(err) //do something;
console.log(result);
});
Recap:
The first example would either find first name Bob or last name Marley.
But the second example would only find either that exact id that I provided or null.
What am I doing wrong?
The MongoDB _id field is a special type of field and needs to be initialised as follows, before it can be used in the query:
new Mongoose.Types.ObjectId("56b426aa1d6c7a642ab1a52d")
or
var ObjectId = require('mongoose').Types.ObjectId;
new ObjectId("56b426aa1d6c7a642ab1a52d");

Mongoose findByIdAndUpdate not returning correct model

I have an issue I've not seen before with the Mongoose findByIdAndUpdate not returning the correct model in the callback.
Here's the code:
var id = args._id;
var updateObj = {updatedDate: Date.now()};
_.extend(updateObj, args);
Model.findByIdAndUpdate(id, updateObj, function(err, model) {
if (err) {
logger.error(modelString +':edit' + modelString +' - ' + err.message);
self.emit('item:failure', 'Failed to edit ' + modelString);
return;
}
self.emit('item:success', model);
});
The original document in the db looks like this:
{
_id: 1234
descriptors: Array[2],
name: 'Test Name 1'
}
The updateObj going in looks like this:
{
_id: 1234
descriptors: Array[2],
name: 'Test Name 2'
}
The model returned from the callback is identical to the original model, not the updatedObj.
If I query the db, it has been updated correctly. It's just not being returned from the database.
This feels like a 'stupid-user' error, but I can't see it. Any ideas greatly appreciated.
In Mongoose 4.0, the default value for the new option of findByIdAndUpdate (and findOneAndUpdate) has changed to false, which means returning the old doc (see #2262 of the release notes). So you need to explicitly set the option to true to get the new version of the doc, after the update is applied:
Model.findByIdAndUpdate(id, updateObj, {new: true}, function(err, model) {...
app.put("/vendor/:id",async (req,res)=>{
res.send(req.params)
await ModelName.findByIdAndUpdate(id, {type: change}, function(err, docs){
if(err){
conslole.log(err)
}else{
console.log(docs)
}
})
})
Example:
app.put("/vendor/:id",async (req,res)=>{
res.send(req.params)
const data = await userModel.findByIdAndUpdate(req.params.id, {isVendor: true},
function(err, docs){
if(err){
conslole.log(err)
}else{
console.log(docs)
}
})
})

Cannot applying find() method with Native MongoDB becaus of ID type

I have a function that is needed to get results.
When I give 1 as _id filter everything is OK.
collectionPersonnel
.find({ '_id' : 1 })
.toArray(function (err, personnel) {
console.log(personnel);
});
If I give filter another way for instance user[0]['personnel_id'] -that is store 1- then I get only [] result;
collectionPersonnel
.find({ '_id' : user[0]['personnel_id'] })
.toArray(function (err, personnel) {
console.log(personnel);
});
And then I've tried another way. But it doesn't work because I used a string(user[0]['personnel_id']) instead of an ObjectID.
var ObjectID = require('mongodb').ObjectID;
var personnelPK_Hex = (user[0]['personnel_id']).toHexString();
var personnelPK = ObjectID.createFromHexString(personnelPK_Hex);
What should I do?
Edit
All of my codes are below;
module.exports = {
show: function(req, res) {
User.native(function(err, collectionUser) {
if(err) {
console.log("There is no exist a User by current_id");
};
collectionUser
.find({'_id' : req.param('id')})
.toArray(function (err, user) {
Personnel.native(function(err, collectionPersonnel) {
if(err) {
// handle error getting mongo collection
console.log("There is no exist a Personel by current _id");
};
if(!collectionPersonnel) {
console.log("There is no exist a Personel by current _id");
};
// var ObjectID = require('mongodb').ObjectID;
// var personnelPK_Hex = (user[0]['personnel_id']).toHexString();
// var personnelPK = ObjectID.createFromHexString(personnelPK_Hex);
collectionPersonnel
.find({ '_id' : user[0].personnel_id })
.toArray(function (err, personnel) {
console.log(personnel);
});
});
});
});
}
};
And console's output is;
[]
Solved
Just like apsillers's said. I had given a numeric _id to collection, incorrectly.
I've fixed _id value and everything is OK.
Thank you all...
user[0]['personnel_id'] might be a string. For Mongo, "1" is different from 1, which is why your literal number 1 worked, but your variable (which holds a string) does not.
Instead, try using a unary plus to convert the string to a number: +user[0]['personnel_id'].
try to use like user[0].personal_id instead of user[0]['personnel_id'] please provide your schema design that would be better to figure out what exactly you are missing.
i tried like this
collectionPersonnel
.find({ '_id' : user[0].personnel_id })
.toArray(function (err, personnel) {
console.log(personnel);
});

MongoDB native driver for Node.js is not returning a result when querying '_id'

I am trying to query my database for a matching '_id' but the results are coming back null, but in the mongodb shell it is coming back with the correct results. Here is the code I am using.
var collection = new mongodb.Collection(client, 'products');
collection.findOne({ _id : 50738ebbe3d87c6beaddb6f2 }, function(err, result){
res.send(result);
console.log(result);
});
I've also tried using,
"ObjectId('50738ebbe3d87c6beaddb6f2')"
but that also come back 'null'.
The correct syntax is:
collection.findOne({ _id : new mongodb.ObjectID('50738ebbe3d87c6beaddb6f2') },
function(err, result){
res.send(result);
console.log(result);
}
);
This will works fine.
You can use BSON for get ObjectID from HEX string.
var mongodb = require('mongodb');
var BSON = mongodb.BSONNative;
var o_id = BSON.ObjectID.createFromHexString(theidID);
collection.findOne({'_id' : o_id}, function(err, document) {
console.log(document);
});

Resources