Node / Mongo无法通过ObjectId找到

时间:2014-11-22 08:59:14

标签: node.js mongodb

我在这里问过这个问题,但没有一个答案对我有用。

我的代码:

var BSON = require('mongodb').BSONPure;

// value is 544d644cf6eea12336f5e0a1
var object_id = BSON.ObjectID.createFromHexString(req.params.id); 
                    }
// Create GET _id query
collection.find(object_id).toArray(
  function (err, data) {
    if (!err) {
      // 200 OK
      return res.status(200).send({success: true, code: 200, count: data.length, results: data});
    } else {
       // 500 Internal Server (Mongodb) 
       console.log(err);
       return res.status(500).send({success: false, code: 500, error: "Internal Server Error"});
    }

我尝试过ObjectId找到五种不同的方法,但没有一种方法有效。以上是我最近的尝试。我没有得到Node的结果。在我做的时候在mongo shell里面:

> db.people.find({_id : ObjectId("544d644cf6eea12336f5e0a1")});
{ "_id" : ObjectId("544d644cf6eea12336f5e0a1"), "name" : "Jim", "age" : 24, "job" : "engineer" }

你可以看到我得到了一个结果。我在这里缺少什么?

4 个答案:

答案 0 :(得分:7)

与mongo shell相同,您需要为find()编写查询对象。这是一个例子:

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

MongoClient.connect('mongodb://localhost:27017/test', function(err, db) {
  db.collection('people', function(err, collection) {
    collection.find({_id: new ObjectId('544d644cf6eea12336f5e0a1')}).toArray(function(err, docs) {
      console.log(docs);
      db.close();
    });
  });
});

您可能还想查看find()ObjectID

的相关文档

答案 1 :(得分:3)

比较您在MongoDB shell和node.js中查询集合的方式。

在MongoDB shell中,您的查询看起来像

{_id : ObjectId("544d644cf6eea12336f5e0a1")}

但在node.js中它只是

ObjectId("544d644cf6eea12336f5e0a1")

请尝试以下代码:

var ObjectID = require('mongodb').ObjectID;
// ...
collection.find({_id : ObjectId("544d644cf6eea12336f5e0a1")}).toArray(function (err, data) {
  // data[0] is your document here
}

如果您在使用node-mongodb-native时遇到麻烦,请尝试使用mongojs。它构建在node-mongodb-native之上,旨在尽可能地模拟MongoDB shell。

答案 2 :(得分:1)

collection.find({_id: object_d}).toArray(...)

答案 3 :(得分:0)

我赞成你所有的答案。在我原始问题的背景下,你的所有答案都是正确的。谢谢您的帮助!问题完全不同,除非你真的想感到无聊,否则我不会厌烦你......

好吧,好吧。我的应用程序从Mongo集合动态构建路由。为了使遍历此路由列表的循环实际工作,必须有一个包含路由创建逻辑的自调用函数,例如:

for (var route in collections) {
                (function () {
                    // Set vars
                    var collection = db.collection(collections[route]);
                    // Create Express GET route
                    app.get('/' + collections[route] + '/:id', function (req, res) {
                        // Return 400 Bad Request error if no params provided
                        if (typeof req.params.id == 'undefined') {
                            return res.status(400).send({
                                success: false,
                                code: 400,
                                error: "No _id parameter provided"
                            });
                        }

                        // Create GET _id query
                        collection.find({_id: new ObjectId(req.params.id)}).toArray(function (err, data) {
                            if (!err) {
                                // 200 OK
                                return res.status(200).send({
                                    success: true,
                                    code: 200,
                                    count: data.length,
                                    results: data[0]
                                });
                            } else {
                                // 500 Internal Server (Mongodb) Error
                                console.log(err);
                                return res.status(500).send({
                                    success: false,
                                    code: 500,
                                    error: "Internal Server Error"
                                });
                            }
                        });
                    });
    }
}

当这个自调用匿名函数不包含逻辑时,路由器只使用集合[route]的最后一个值,所以对/ accounts /:id的调用将对请求进行字段化(因为路由确实存在),但实际上它将指向Mongo中的人员集合,因为这是数组中的最后一个值(因为在最初运行循环时不强制评估它)。我希望这种解释是有道理的。无论如何,我不能忘记使用(function(){})();

相关问题