Search code examples
node.jsmongodbsails.jsmongodb-querynode-mongodb-native

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...


Solution

  • 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'].