2012-10-15 48 views
12

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'}); 
}); 

Trả lời

33

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')}); 
}); 
+0

Nó hoạt động! Cảm ơn bạn) – Sable

+0

Có thể xóa mảng id cùng một lúc không? – Denis

+1

@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

4

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"); 
    }); 
}); 
Các vấn đề liên quan