Mongoose Query.prototype.updateOne()方法

Mongoose Query.prototype.updateOne()方法

Mongoose的 Query API.prototype.updateOne() 方法是用于Query对象的。它允许我们更新集合中的文档。无论multi选项的值如何,MongoDB都会更新与过滤器匹配的第一个文档。让我们通过一个示例了解 updateOne() 方法。

语法:

Model.updateOne( filter, update, options, callback );

参数: 此方法接受四个参数,如下所述:

  • filter: 用于指定过滤条件。它的形式是一个对象。
  • update: 用于指定更新对象。
  • options: 用于指定各种属性的对象形式。
  • callback: 用于指定回调函数。

返回值: 该方法返回查询对象并更新文档的最新值。

设置Node.js Mongoose模块:

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

npm init

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

npm install mongoose

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

Mongoose Query.prototype.updateOne()方法

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

Mongoose Query.prototype.updateOne()方法

示例1: 下面的示例展示了Mongoose Query updateOne() 方法的基本功能,使用then和catch块。

// Require mongoose module 
const mongoose = require("mongoose"); 
  
// Set Up the Database connection 
const URI = "mongodb://localhost:27017/geeksforgeeks"
  
const connectionObject = mongoose.createConnection(URI, { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}); 
  
const studentSchema = new mongoose.Schema({ 
    name: { type: String }, 
    age: { type: Number }, 
    rollNumber: { type: Number }, 
}); 
  
const Student = connectionObject.model('Student', studentSchema); 
  
Student.updateOne( 
    { name: 'Student3' }, { age: 33 } 
).then(result => { 
    console.log(result); 
})

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

node app.js

输出:

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

使用Robo3T GUI工具的数据库的GUI表示:

Mongoose Query.prototype.updateOne()方法

示例2: 下面的示例演示了Mongoose Query updateOne() 方法的基本功能,使用异步函数和回调promise处理功能。

// Require mongoose module 
const mongoose = require("mongoose"); 
  
// Set Up the Database connection 
const URI = "mongodb://localhost:27017/geeksforgeeks"
  
const connectionObject = mongoose.createConnection(URI, { 
    useNewUrlParser: true, 
    useUnifiedTopology: true, 
}); 
  
const studentSchema = new mongoose.Schema({ 
    name: { type: String }, 
    age: { type: Number }, 
    rollNumber: { type: Number }, 
}); 
  
const Student =  
    connectionObject.model('Student', studentSchema); 
  
(async () => { 
    Student.updateOne( 
        { rollNumber: 176 }, { name: 'S2' },  
        (error, result) => { 
            if (error) { 
                console.log('Error', error); 
            } else { 
                console.log('Result', result); 
            } 
        }) 
})();

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

node app.js

输出:

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

使用Robo3T GUI工具的数据库的GUI表示:

Mongoose Query.prototype.updateOne()方法

参考: https://mongoosejs.com/docs/api/query.html#query_Query-updateOne

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程