Mongoose Document Model.updateOne()函数

Mongoose Document Model.updateOne()函数

Mongoose API的Model.updateOne()方法 用于更新集合中的文档。不管multi选项的值如何,该方法将更新与过滤器匹配的第一个文档。

Model.updateOne()方法接受四个参数:

  • filter: 一个用于过滤需要更新的文档的对象。
  • update: 一个包含键值对的对象数组,其中键是文档中的列/属性。
  • options: 一个带有各种属性的对象。
  • callback: 一旦执行完成,将运行的回调函数。

设置Node.js应用程序:

步骤1: 使用以下命令创建一个Node.js应用程序:

npm init

步骤2: 创建NodeJS应用程序后,使用以下命令安装所需的模块:

npm install mongoose

项目结构: 项目的结构将如下所示:

Mongoose Document Model.updateOne()函数

数据库结构:

数据库结构将如下所示,以下文档存在于集合中。

Mongoose Document Model.updateOne()函数

示例1:

在这个示例中,我们使用mongoose建立了一个数据库连接,并在customerSchema上定义了一个模型。模型中有两列:“name”和“orderCount”。最后,我们在Customer模型上使用updateOne()方法,该方法将从集合中筛选出一个文档,并更新该文档。在这个示例中,我们根据name字段筛选文档,并将orderCount的值更新为0。

app.js:

将以下代码写入app.js文件中:

// Require mongoose module 
const mongoose = require('mongoose'); 
  
// Set Up the Database connection 
mongoose.connect( 
    'mongodb://localhost:27017/geeksforgeeks', { 
    useNewUrlParser: true, 
    useUnifiedTopology: true
}) 
  
// Defining customerSchema schema 
const customerSchema = new mongoose.Schema( 
    { name: String, orderCount: Number } 
) 
  
// Defining customerSchema model 
const Customer = mongoose.model('Customer', customerSchema); 
Customer.updateOne({ name: 'Rahul' }, { orderCount: 0 }) 
    .then(result => { 
    console.log(result) 
});

运行程序的步骤: 从项目的根目录中运行应用程序,请执行以下命令:

node app.js

输出:

{
  acknowledged: true, 
  modifiedCount: 1,
  upsertedId: null, 
  upsertedCount: 0, 
  matchedCount: 1 
}

你可以使用任何图形化界面工具来表示数据库。在这里,我使用了Robo3T图形界面工具进行图形化表示。

Mongoose Document Model.updateOne()函数

示例2: 在此示例中,我们根据name字段进行文档过滤,并将”name”值更新为”Customer2 Updated”。

app.js: 将以下代码写入app.js文件中:

// Require mongoose module 
const mongoose = require('mongoose'); 
  
// Set Up the Database connection 
mongoose.connect( 
    'mongodb://localhost:27017/geeksforgeeks', { 
    useNewUrlParser: true, 
    useUnifiedTopology: true
}) 
  
// Defining customerSchema schema 
const customerSchema = new mongoose.Schema( 
    { name: String, orderCount: Number } 
) 
  
// Defining customerSchema model 
const Customer = mongoose.model( 
    'Customer', customerSchema); 
Customer.updateOne({ name: ['Customer2'] },  
    { name: "Customer2 Updated" }).then(result => { 
    console.log(result) 
});

运行程序的步骤: 从项目的根目录中执行以下命令来运行应用程序:

node app.js

输出:

{
  acknowledged: true,
  modifiedCount: 1,  
  upsertedId: null,  
  upsertedCount: 0,  
  matchedCount: 1    
}

您可以使用任何图形用户界面工具来显示数据库的图形形式。这里,我使用了Robo3T图形用户界面工具进行图形表示。

Mongoose Document Model.updateOne()函数

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

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程