ozomer / node-red-contrib-mongodb2

MongoDB driver node for Node-RED
Apache License 2.0
15 stars 19 forks source link

Does projection filter work with find.toArray ? #18

Closed Sherulez closed 6 years ago

Sherulez commented 6 years ago

Hi,

Does .projection work with the find.toArray operation?

var myMsg = {}; 
myMsg.collection = 'sonde_int';
myMsg.operation = 'find.toArray';
myMsg.payload = {'subject': 'temp'};
myMsg.projection = {'value': 1 , '_id': 0};
myMsg.sort = {'timestamp': -1};
//For httpResponse 
myMsg.req = msg.reg; 
myMsg.res = msg.res; 
return myMsg ;

I read here node-mongodb

projection : Limits the fields to return for all matching documents.

My function always returns an array with all the fields. (even _id). Is it normal ? I can always change the output like this with a new function :

var myMsg =[];
for (var i = 0; i < msg.payload.length; i++) {
myMsg .push(msg.payload[i].value) };
msg.payload = myMsg ;
return  msg;

But I would like to know if it was possible to limit the fields at the query level ? Thanks in advance.

Sherulez commented 6 years ago

Looking a little bit I came across this problem of JonSilver #8. (ty 🥇) And indeed, it is necessary to include the projection in the payload like this for example :

myMsg.payload = [{'subject': 'temp'}, {'value' : 1, '_id': 0}];
ozomer commented 6 years ago

Yes, msg.payload should be an array of all the parameters that are passed to find(...). The documentation of mongodb-find does not mention that the function can accept more than one parameter, but it does. A more "correct" way would be something like: myMsg.payload = [{"subject": "temp"}, {"fields": {"value": 1, "_id": 0}}]; Because the second parameter is actually an "options" parameter, that can contain many type of options - "fields" for projection, but also others like "skip", "limit", etc. The "find" function in the mongodb library actually iterates all the keys in the options parameter, and if it detects unfamiliar names it treats the whole options object as "fields" for projection.