【发布时间】: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