2014-04-28 55 views
0

我想要生成一個用戶id列表,我想用它們在mongodb集合中找到它們。mongodb搜索id列表

如果我做了以下操作,我會在第3行收到一條錯誤消息:「undefined不是函數」。

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

如果我在這裏用問答形式:Mongo, find through list of ids它說的ObjectId是不確定的,它崩潰。如果這是唯一的解決方案,我該如何定義該解決方案的ObjectId才能工作?

編輯:

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

結果:

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

但因爲當我使用BSON崩潰發生我看不到任何東西的IDS。如果我搜索這個列表,結果是空的。由於缺少BSON.ObjectId我猜想,因爲此搜索適用於單個對象。

+1

怎麼樣

您可以從mongoose這種方式導入ObjectId類型JSON.stringify'ids'以查看包含的內容。看看你自己或添加到你的問題。但是,既然你在「第三線」上說過,你真的導入了BSON嗎? –

+0

環境:mongodb shell,nodejs,...? – throrin19

+0

我正在使用nodejs。 –

回答

3

使用本地驅動程序mongodb可以使用

ObjectID = require('mongodb').ObjectID類型。見documentation

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

下面的代碼給了我一個很好的結果

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

來源爲mongooseCan't find documents searching by ObjectId using Mongoose