当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


Mongoose Document Model.updateOne()用法及代码示例


Mongoose API 的 Model.updateOne() 方法用于更新集合中的文档。此方法将更新第一个与过滤器匹配的文档,无论 multi-option 的值如何。

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

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

设置 Node.js 应用程序:

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

npm init

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

npm install mongoose

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

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

示例 1:在此示例中,我们使用 mongoose 建立了数据库连接,并通过 customerSchema 定义了模型,具有两列 “name” 和 “orderCount”。最后,我们在 Customer 模型上使用 updateOne() 方法,该方法将从集合中过滤单个文档并更新该文档。在此示例中,我们根据名称字段过滤文档并将 “orderCount” 值更新为 0。

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

Javascript


// 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 
}

您可以使用任何 GUI 工具以图形形式表示数据库。在这里,我使用 Robo3T GUI 工具进行图形表示。

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

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

Javascript


// 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    
}

您可以使用任何 GUI 工具以图形形式表示数据库。在这里,我使用 Robo3T GUI 工具进行图形表示。

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



相关用法


注:本文由纯净天空筛选整理自kartikmukati大神的英文原创作品 Mongoose Document Model.updateOne() API。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。