2016-06-15 48 views
1

我一直在試圖理解爲什麼這個刪除查詢不能工作幾天,我只是看不到問題。
我已經嘗試了許多不同的刪除查詢,如deleteOne,findOneAndDelete,deleteMany,但都沒有工作。
我用node.js的Node.js刪除查詢「mongodb」

mongo.connect(serverAddress, (err, db) => { 
//(db connection is ok, server can find and create documents) 

    var doc = db.collection('myCollection'), 
    docToDelete = "575807172154b7a019ebf6db"; 
    //I can see the same document id on my database 

    doc.deleteOne({"_id":docToDelete}, (err, results) => { 
     console.log(`Request success : ${results.result.ok}, documents deleted : ${results.result.n}`); 
     //Request success : 1, documents deleted : 0, the document is still on my database 
    }); 
} 
//the doc var is the same I use to add/find documents (and it works). 

的「mongodb的」客戶端當我使用相同的查詢像MongoClient軟件,它的工作原理。
我已經嘗試了許多解決方案張貼在這個網站,並抱歉,如果錯誤太明顯,但我完全失去了。
感謝您的幫助。

回答

1

問題是數據庫中的_id類型是ObjectId,但在您的查詢中它是String。你必須嚴格要求,否則查詢將不匹配文檔。

試試這個:

const mongodb = require('mongodb'); 
... 
doc.deleteOne({ _id : mongodb.ObjectId(docToDelete) }, (err, results) => { 
    ... 
}); 
+0

我完全錯了,打消了我的答案,一爲您 –

+0

非常感謝!我記得在mongo文檔的某個地方看過這個ObjectId方法,但我沒有建立連接...... – Razshal