Mongoose OR operator with _id - node.js

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

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

Concatanate Variable And Query MongoDB

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

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

Is it possible to return only a certain fields when inserting a new document?

I nedd to get the new document back with _id field only. Something like this:
db.users.insert({name: 'Jonh', age: 27}, {_id: true} , function (err, user) {
if (err) {}
// need to be user with only _id field.
});
How can I do this?
UPDATED
The second parameter to the insert callback is always an array of the inserted objects, and you can't prevent the other fields from being included. However, you can use Array#map to create the result you're looking for:
db.users.insert({name: 'Jonh', age: 27}, {_id: true} , function (err, users) {
if (err) {}
users = users.map(function(user) {
return {_id: user._id};
});
// users now contains objects with just the _id field
});

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