db.collection('infochanges').remove({"_id":idvalue}).then(function(){})
會報錯,這里需要將idvalue轉換成mongodb默認的_id字段的objectid類型
於是,引入模塊(mongoDB3.6)
var ObjectId = require('mongodb').ObjectID;//Work
其他的mongoDB版本可嘗試
var ObjectId = require('mongodb').ObjectId;//Work
引用完成之后
db.collection('infochanges').remove({"_id":{"_id":ObjectId(idvalue)}).then(function(){})
此時,你會發現並不能通過上述操作成功刪除數據,而是報錯:
TypeError:Cannot convert undefined or null to object
重點:請使用findAndRemove
db.collection('infochanges').findAndRemove({"_id":ObjectId(index)}).then(function(){})
通過_id刪除docs要用findAndRemove,remove不起作用(3.6版本)
上面給的寫法,也可以省略 .then()。 直接通過傳參的方式。 都是回調函數,等待異步執行完才執行。
例:
db.collection('infochanges').findAndRemove({"_id":ObjectId(index)}), function(){})
【注】 findAndRemove 現在也被棄用了,被更換為findOneAndDelete
希望能給各位遇到同樣問題的道友一些幫助,也請各位大神多多指點,輕噴。