0

I'm trying generate a list of user ids which I want to use to find them in a mongodb collection.

If I do the following I get an error on the 3rd line saying: "undefined is not a function".

var ids = [];
for (var i = 0; i < item.users.length; i++) {
    ids.push(new BSON.ObjectId(item.users[i].appProfileId));
}
db.collection('users', function(err, collection) {
    collection.find({_id: {$in: ids}}, function(err, users) {
        if (err) {
            console.log(err);
        } else {
            console.log("USERS to push to: " + JSON.stringify(users));
            pusher(users, from, channelId);
        }
    });
});

If I use the answer form here: Mongo, find through list of ids it says that ObjectId is undefined and it crashes. If that is the only solution, how to I define ObjectId for that solution to work?

EDIT:

var ids = [];
for (var i = 0; i < item.users.length; i++) {
    ids.push(item.users[i].appProfileId);
}
console.log("ids: " + JSON.stringify(ids));

results in:

"ids": [
    "535cf8e3df3aaa723fc9cad1",
    "535cf8e3df3aaa723fc9cad1",
    "535cf8e3df3aaa723fc9cad1"
]

But since crash happens when I use BSON I can't see anything in ids. And if I search for this list the result is empty. Because of the missing BSON.ObjectId I guess since this search works for a single object.

Community
  • 1
  • 1
just_user
  • 11,769
  • 19
  • 90
  • 135
  • 1
    How about a JSON.stringify on `ids` to see what that contains. Look at that yourself or add to your question. But also since you say on the "third line", did you actually import BSON? – Neil Lunn Apr 28 '14 at 11:42
  • Environment : mongodb shell, nodejs, ... ? – throrin19 Apr 28 '14 at 12:21
  • possible duplicate of [Can't find documents searching by ObjectId using Mongoose](http://stackoverflow.com/questions/7878557/cant-find-documents-searching-by-objectid-using-mongoose) – Neil Lunn Apr 28 '14 at 16:07

1 Answers1

3

Using the native driver mongodb you can use the

ObjectID = require('mongodb').ObjectID type. See the documentation.

You can import the ObjectId type from mongoose this way:

var ObjectId = require('mongoose').Types.ObjectId;

The below code gives me a good result

var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongoose').Types.ObjectId
//var ObjectId = require('mongodb').ObjectID

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
if (err) throw err;

var ids = [new ObjectId("535e768860e89147eb66e961"), new ObjectId("535e768c60e89147eb66e962")]
var c = db.collection('users').find({
    '_id': {
        '$in': ids
    }
})

c.each(function(err, result) {
    if (err)
        throw err
    console.log(JSON.stringify(result))
})
});

Source for mongoose: Can't find documents searching by ObjectId using Mongoose

Community
  • 1
  • 1
Pio
  • 4,044
  • 11
  • 46
  • 81