簡體   English   中英

使用ID從MongoDB獲取對象

[英]Getting an object from MongoDB using its id

首先讓我解釋一下我的問題。 我正在嘗試從URL獲取ID,並使用它在database(MongoDB)中查找記錄。 我在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();
               });
           });
        }
    });
});

如果將ID硬編碼為1,則會得到記錄。但是,這種方式並沒有得到記錄。 但是我已經使用console.log檢查了我通過URL獲得的ID也是1。

將字符串轉換為整數

如果url中有一個變量-它是一個字符串。 如果要使用數字查詢數據庫,則需要將其強制轉換為數字以在查詢中使用:

obj_to_search={_id: parseInt(to_update,10)};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM