Tại sao tôi không thể xóa bản ghi bằng _id?Xóa bản ghi theo id?
Code:
db.collection('posts', function(err, collection) {
collection.remove({_id: '4d512b45cc9374271b00000f'});
});
Tại sao tôi không thể xóa bản ghi bằng _id?Xóa bản ghi theo id?
Code:
db.collection('posts', function(err, collection) {
collection.remove({_id: '4d512b45cc9374271b00000f'});
});
Bạn cần phải vượt qua giá trị _id
như một ObjectId, không phải là một chuỗi:
var mongodb = require('mongodb');
db.collection('posts', function(err, collection) {
collection.deleteOne({_id: new mongodb.ObjectID('4d512b45cc9374271b00000f')});
});
MongoDB hiện nay đã đánh dấu phương pháp loại bỏ như phản đối. Nó đã được thay thế bằng hai phương thức riêng biệt: deleteOne và deleteMany.
Dưới đây là có liên quan hướng dẫn bắt đầu của họ: https://docs.mongodb.org/getting-started/node/remove/
và đây là một ví dụ nhanh:
var mongodb = require('mongodb');
db.collection('posts', function(err, collection) {
collection.deleteOne({_id: new mongodb.ObjectID('4d512b45cc9374271b00000f')}, function(err, results) {
if (err){
console.log("failed");
throw err;
}
console.log("success");
});
});
Nó hoạt động! Cảm ơn bạn) – Sable
Có thể xóa mảng id cùng một lúc không? – Denis
@Denis Chắc chắn, chỉ cần sử dụng ['$ in'] (http://docs.mongodb.org/manual/reference/operator/query/in/#op._S_in):' {_id: {$ in: idsArray} } ' – JohnnyHK