Mongoose Document Model create()函数
Mongoose API 的 Model.create() 方法用于在集合中创建单个或多个文档。当我们在任何模型上使用 create() 方法时,默认情况下 Mongoose 会内部触发 save()。
语法:
Model.create()
参数: Model.create()方法接受三个参数:
- docs: 它是一个键值对对象,将被插入到集合中。
- options: 它是一个具有各种属性的对象。
- callback: 它是一个回调函数,一旦执行完成将被执行。
返回值: Model.create()函数返回一个promise。
设置Node.js应用程序:
步骤1: 使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需模块:
npm install mongoose
项目结构: 项目结构如下所示:
示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并定义了一个名为customerSchema的模型,它有两个字段“name”和“orderCount”。最后,在Customer模型上创建了一个单一的文档。
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);
// creating document using create method
Customer.create({ name: 'Rahul', orderCount: 5 })
.then(result => {
console.log(result)
})
运行程序的步骤: 从项目的根目录执行以下命令来运行应用程序:
node app.js
输出:
{
name: 'Rahul',
orderCount: 5,
_id: new ObjectId("6304e68407a431f560473ac2"),
__v: 0
}
使用Robo3T GUI工具的数据库的GUI表示
示例2: 在本示例中,我们使用mongoose建立了数据库连接,并在customerSchema上定义了模型,该模型有两列:“name”和“orderCount”。最后,我们在Customer模型上同时创建多个文档。
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);
// Creating document using create method
Customer.create([{
name: 'Customer2',
orderCount: 10
},
{ name: 'Customer3', orderCount: 20 }])
.then(result => {
console.log(result)
})
运行程序的步骤:
要运行该应用程序,请从项目的根目录执行以下命令:
node app.js
输出:
[
{
name: 'Customer2',
orderCount: 10,
_id: new ObjectId("6304e7c8c21ca86f5ea6fce3"),
__v: 0
},
{
name: 'Customer3',
orderCount: 20,
_id: new ObjectId("6304e7c8c21ca86f5ea6fce4"),
__v: 0
}
]
使用Robo3T GUI工具的数据库GUI表示
参考: https://mongoosejs.com/docs/api/model.html#model_Model-create