Mongoose 查询Model.deleteOne() API

Mongoose 查询Model.deleteOne() API

Mongoose 模块是Node.js最强大的外部模块之一。为了将代码及其表示从MongoDB转移到Node.js服务器,Mongoose是一个MongoDB的ODM(对象数据库建模)工具。

deleteOne() 函数用于删除满足条件的第一个文档。

语法:

deleteOne(conditions, options)

参数:

  • conditions: 过滤条件。
  • options: 选项对象。

返回值: 带有删除文档数量的对象。

安装 mongoose 模块:

步骤1: 你可以使用以下命令来安装此包。

npm install mongoose

步骤2: 安装了 mongoose 模块后,可以在命令提示符中使用以下命令检查 mongoose 版本。

npm version mongoose

步骤3: 之后,您只需创建一个文件夹并添加一个文件,例如index.js。要运行此文件,您需要运行以下命令。

node index.js

以下是我在下面的示例中使用的数据集。

Mongoose 查询Model.deleteOne() API

示例1: 在这个示例中,我们尝试删除一个 _id=11 的文档。由于我们使用的数据中没有这样的文档,因此不会删除任何文档。

const Person = require("../mongoose/model/person"); 
const mongoose = require("mongoose"); 
  
let mongoDB = mongoose.connect 
    ("mongodb://localhost:27017/person", { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}); 
  
let db = mongoose.connection; 
db.on("error", console.error.bind(console,  
    "MongoDB Connection Error")); 
  
(async () => { 
    const res = await Person.deleteOne( 
        { _id: 11 }, 
    ); 
    console.log(`Number of Deleted Documents: ${res.deletedCount}`); 
})(); 

输出:

Mongoose 查询Model.deleteOne() API

示例2: 在此示例中,我们尝试删除一个last_name为Bourgeois的文档。由于存在符合条件的文档,它将被删除。

const Person = require("../mongoose/model/person"); 
const mongoose = require("mongoose"); 
  
let mongoDB = mongoose.connect 
    ("mongodb://localhost:27017/person", { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}); 
  
let db = mongoose.connection; 
db.on("error", console.error.bind(console, " 
    MongoDB Connection Error")); 
  
(async () => { 
    const res = await Person.deleteOne 
        ({ last_name: "Bourgeois" }); 
    console.log(`Number of Deleted Documents:  
        ${res.deletedCount}`); 
})(); 

输出:

Mongoose 查询Model.deleteOne() API

参考: https://mongoosejs.com/docs/api/model.html#model_Model-deleteOne

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程