[英]Getting an object from MongoDB using its id
Let me explain my problem first. 首先让我解释一下我的问题。 I am trying to get the ID from URL and use it to find a record in the database(MongoDB).
我正在尝试从URL获取ID,并使用它在database(MongoDB)中查找记录。 The following code I have in NodeJS Express App.
我在NodeJS Express App中拥有以下代码。
app.post('/dashboard/profile/update/:id',function(req,res){
var to_update=req.params.id;
var firstName=req.body.fname;
obj_to_search={_id:to_update};
db.open(function(err, dbs) {
if(!err) {
dbs.collection('project',function(err, collection) {
//update
collection.findOne(obj_to_search, function(err, result) {
if (err) {
throw err;
} else {
res.send(result);
}
dbs.close();
});
});
}
});
});
I am getting the record if I hard code the ID to 1. But I am not getting the record by this way. 如果将ID硬编码为1,则会得到记录。但是,这种方式并没有得到记录。 However I have checked using
console.log
the ID i am getting through URL is also 1. 但是我已经使用
console.log
检查了我通过URL获得的ID也是1。
If a variable is in the url - it's a string. 如果url中有一个变量-它是一个字符串。 If you're wanting to query the database with a number, you'll need to cast it to a number for use in the query:
如果要使用数字查询数据库,则需要将其强制转换为数字以在查询中使用:
obj_to_search={_id: parseInt(to_update,10)};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.