Mongoose Document Model.replaceOne()函数
Mongoose API的 Model.replaceOne() 方法用于替换集合中的任何一个文档。此方法与update方法相同,但它使用给定的文档替换MongoDB的现有文档,并可使用任何原子操作符,如$set。
语法:
Model.replaceOne()
参数: Model.replaceOne()方法接受四个参数:
- filter: 它是一个用于过滤所有需要更新的匹配字段的对象。
- doc: 它是一个具有将替换现有字段的字段的对象。
- options: 它是一个具有各种属性的对象。
- callback: 它是一个在执行完成后运行的回调函数。
返回类型: Model.replaceOne()函数返回一个Promise。结果包含以下键和值或属性的对象。
设置Node.js应用程序:
步骤1: 使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需模块:
npm install mongoose
项目结构: 项目的结构将如下所示:
数据库结构: 数据库结构将如下所示,集合中包含以下文档。
示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在customerSchema上定义了一个模型,包含三个列或字段“name”,“orderCount”和“superUser”。最后,我们在Customer模型上使用replaceOne()方法,该方法将根据作为方法第一个参数的条件替换文档。并将这些文档替换为作为方法第二个参数的对象中给定的字段。在这个示例中,我们根据“_id”筛选文档,并用对象中提供的字段替换其值作为方法的第二个参数。
- app.js: 在app.js文件中写下以下代码:
// Importing the 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, superUser: Boolean }
)
// Defining customerSchema model
const Customer = mongoose.model('Customer', customerSchema);
// replaceOne() method
Customer.replaceOne({ _id: '630ca42f5e5d4f1de37cf654' },
{ name: 'Customer3', orderCount: 100, superUser: true })
.then(result => {
console.log(result)
})
运行该程序的步骤:
要运行该应用程序,请从项目根目录执行以下命令:
node app.js
输出:
{
acknowledged: true,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1
}
使用Robo3T GUI工具的数据库GUI表示
示例2: 在这个示例中,我们根据“_id”来筛选文档,并用对象的第二个参数提供的字段替换其值。如果你看到GUI输出,我们将“name”字段从“Customer2”替换成了“Customer2 Example 2”,并且还修改了“orderCount”的值,这个功能是通过使用任何原子操作符(比如$set)来实现的。
- app.js: 将以下代码写入app.js文件中:
// Importing the 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, superUser: Boolean }
)
// Defining customerSchema model
const Customer = mongoose.model('Customer', customerSchema);
// Calling the replaceOne() method.
Customer.replaceOne({ _id: '630ca4260edd88312bf28db1' },
{
name: 'Customer2 Example2',
orderCount: 0, superUser: false
}).
then(result => {
console.log(result)
})
运行程序的步骤: 从项目的根目录执行以下命令来运行应用程序:
node app.js
输出:
{
acknowledged: true,
modifiedCount: 1,
upsertedId: null,
upsertedCount: 0,
matchedCount: 1
}
使用Robo3T GUI工具的数据库的GUI表示
参考: **** https://mongoosejs.com/docs/api/model.html#model_Model-replaceOne