如何在 Mongoose 中按 ID 删除文档
目前没有调用的方法 deleteById()
在 Mongoose 中。 然而有 deleteOne()
带有参数的方法, filter
指示要删除的文档。 只需通过 _id
作为 filter
并且文档将被删除。
const testSchema = new mongoose.Schema({
name: String
});
const Test = mongoose.model('Test', testSchema);
async function run() {
const entry = await Test.create({ name: 'Masteringjs.io' });
console.log(await Test.countDocuments({ _id: entry._id })); // 1
// Delete the document by its _id
await Test.deleteOne({ _id: entry._id });
console.log(await Test.countDocuments({ _id: entry._id })); // 0
}
run();
使用实例方法
你也可以让 deleteById()
模式上的 Mongoose 静态 ,这将使 deleteById()
模型上的一个函数,如下所示。
const testSchema = new mongoose.Schema({
name: String
});
testSchema.statics.deleteById = function(_id) {
return this.deleteOne({ _id: _id })
};
const Test = mongoose.model('Test', testSchema);
async function run() {
const entry = await Test.create({ name: 'Masteringjs' });
console.log(await Test.countDocuments({ _id: entry._id })); // 1
await Test.deleteById(entry._id);
console.log(await Test.countDocuments({ _id: entry._id })); // 0
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论