I am using MONGOHQ and NODE.JS to make an application, I would really like the help of someone because I have a big problem, I tried everything and look everywhere, so this is my last option.
I have this query on a node JS post:
{ propertyId: '53f4f097f28c16cf87a15664' }
This query is being used here :
db.collection('animal').find(req.body.query).toArray(function (err, animals) {
res.send(
(err === null) ? { status: 'ok', result: animals } : { status: err }
);
});
And its working FINE !
Now the problem :
What I want is to add another query to the find, without modifying the req.body.query.
What I have is a list of _id (not ObjectIds), called myArray, and it's like :
[ '12312123' , '78787878' ]
So I am doing this :
db.collection('animal').find({ $and : [ req.body.query, { '_id' : { $in : myArray} } ] }).toArray(function (err, animals) {
res.send(
(err === null) ? { status: 'ok', result: animals } : { status: err }
);
});
And its giving me an empty list.
But instead, if I do the same query on mongohq like :
find({$and : [ { propertyId: '53f4f097f28c16cf87a15664' }, { '_id' : { $in :['12312123', '78787878']} } ] })
Its giving me a list with 1 element that matches the criteria:
{
_id: "12312123",
propertyId: "53f4f097f28c16cf87a15664",
active: "true"
}
Does anyone have an idea ? I would be glad to hear !
Thanks
Michael
Your question doesn't specify why you don't want to modify req.body.query
, but there could be many reasons for that, so here's how you could make a copy of it before modifying it, that way you don't even need to bother with $and
:
var query = req.body.query;
//make a copy of the query object
var queryCopy = {};
for (var i in query) {
queryCopy[i] = query[i];
}
//add your additional conditions
queryCopy._id: { $in : myArray} };
var result = db.collection('animal').find(queryCopy);
//result.toArray(...)
Note that this approach only creates a shallow copy of the object, which is fine in this case because you're not modifying any nested objects or arrays. If you want you could add a function for creating shallow copies, here's one you could use (I prefer to use Object.keys()
for this generic function instead of the var i in...
approach above because it doesn't unnecessarily copy prototype properties [although sometimes you might want that] but it doesn't make a difference in your case.)
function shallowCopy(obj) {
var copy = {},
keys = Object.keys(obj),
len = keys.length;
for (var i=0; i < len; i++) {
copy[keys[i]] = obj[keys[i]];
}
return copy;
}
If you DO need to create a deep copy of an object because you want to modify nested objects and arrays without affecting the original object, then you'll need to use a function specifically designed for that purpose, since Javascript doesn't provide a native function to do that. Here's a deep copy function (from my answer to a question about that) - use the more robust version since that has proper support for arrays, regular expressions, and dates: