Mongoose document prototype。updateOne()函数
prototype.updateOne() 是Mongoose API中用于更新集合中文档的方法。该方法可用于Mongoose文档,并且您可以使用该文档一次性更新多个字段。
语法:
doc.updateOne()
参数: prototype.updateOne() 方法接受三个参数:
- doc: 这是一个具有字段和值以进行更新的对象。
- options: 这是一个具有各种属性的对象。
- callback: 这是一个在执行完成后运行的回调函数。
返回值: prototype.updateOne() 函数返回一个 promise。结果包含一个具有各种属性的对象。
设置 Node.js 应用程序:
步骤1: 使用以下命令创建一个 Node.js 应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需模块:
npm install mongoose
项目结构: 项目的结构将如下所示:
数据库结构: 数据库结构将如下所示,集合中包含以下文档。
示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并定义了用户模式(userSchema)的模型,该模型有两个列或字段“name”和“age”。最后,我们使用 updateOne() 方法在User模型的文档对象上进行更新,一旦我们执行代码,该模型将被更新。在这个示例中,我们定义了一个名为“findDoc”的异步函数,它负责在集合中查找文档,并使用 updateOne() 方法在文档对象上更新文档。我们更新了User集合的name字段。
- 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,
});
const userSchema = new mongoose.Schema({
name: String,
age: Number
});
// Defining userSchema model
const User = mongoose.model("User", userSchema);
let doc;
const findDoc = async () => {
doc = await User.findById("63203694182cd3c22ea480ff")
const result = await doc.updateOne({ name: "User1 Update" })
console.log(result)
}
findDoc()
运行程序的步骤: 要运行该应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
{
acknowledged: true,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1
}
通过Robo3T GUI工具在GUI中表示的数据库:
示例2: 在该示例中,我们定义了一个名为“findDoc”的异步函数,它负责在集合中查找文档,并使用 updateOne() 方法在文档对象上更新文档。我们正在更新User集合的age字段。
- 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,
});
const userSchema = new mongoose.Schema({
name: String,
age: Number
});
// Defining userSchema model
const User = mongoose.model("User", userSchema);
let doc;
const findDoc = async () => {
doc = await User.findById("63203694182cd3c22ea480ff")
doc.updateOne({ age: 100 }).then(result => {
console.log(result)
})
}
findDoc()
运行程序的步骤: 要运行该应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
{
acknowledged: true,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1
}
使用Robo3T GUI工具的GUI数据库表示:
参考: https://mongoosejs.com/docs/api/document.html#document_Document-updateOne