【问题标题】:Why can't my query object use _id properly?为什么我的查询对象不能正确使用 _id?
【发布时间】:2014-08-03 12:37:32
【问题描述】:

我正在尝试使用 Express 和 MongoDB 编写 Node.js Web API。我正在从 GET 请求中动态解析 req.query 对象(Express 的查询字符串存储/解析器),并使用查询字符串对更新名为“查询”的对象,以便我可以在数据库集合中找到与查询字符串参数匹配的文档.例如,一个 localhost:3000//users?name=John&last=Smith 将修改查询对象,以便我们仅查找 name 字段为 John 且 last 字段为 Smith 的记录。我们也可以不发送这些参数,只发送一个或多个。问题是当我尝试发送这样的查询字符串时:

localhost:3000//users?_id=1

这不返回任何内容。当我使用终端(windows cmd)直接访问数据库并运行此查询(db.Users.find({_id:1}))时,它工作正常并按预期返回。此外,console.log(query._id) 返回 1,所以我知道该对象正在按我的预期存储参数。

var query = {};
//Iterate through query string parameters as a Get request
//Add them to the query object, (add them as object properties)
for(var propName in req.query) {
    query[propName] = req.query[propName];
}
db.collection("Users", function(err, collection) {
        if(!err) {
            collection.find(query, {limit: 100},function(err, cursor) {
                if(!err) {
                    cursor.toArray(function(err, arr) {
                        if(!err) {
                            console.log(arr);
                            res.send(arr);
                        } else {
                            console.log("Failed to turn cursor to array: "+err);
                        }
                    });
                } else {
                    console.log("Find failed: "+err);
                }
            });
        } else {
            console.log("Failed opening collection: "+err);
        }
    });

【问题讨论】:

    标签: node.js mongodb http express


    【解决方案1】:

    这是因为 MongoDB 文档中的 _id 值是数字 1,但您使用字符串 '1' 查询它(所有 req.query 字段都是字符串)。

    可能的解决方案是将字段解析为数字:

    if (propName === '_id') {
        query[propName] = parseInt(query[propName], 10);
    }
    

    或者使用 Mongoose 之类的东西,它会根据架构定义为您进行这种类型的转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-12
      • 1970-01-01
      • 2012-12-26
      • 1970-01-01
      • 2023-03-23
      • 2011-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多