Mongoose Schema Connection.prototype.model() 函数
Mongoose Schema API 的 Connection.prototype.model() 用于 Connection 对象。它允许我们在 MongoDB 数据库中为特定的连接对象定义新的模型。它用于定义和检索数据库中的模型。让我们通过一个示例来理解 models() 方法。
语法:
connectionObject.model( name, schema, collection, options );
参数: 此方法接受四个参数,如下所述:
- name: 用于指定模型的名称。
- schema: 用于定义模型的模式。
- collection: 用于指定集合的名称。这是一个可选字段,如果我们不提供集合的名称,mongoose将使用模型名称。
- options: 用于定义模型上的各种属性。
返回值: 它返回基于名称和我们为其定义的模式的完整模型。
设置Node.js应用程序:
步骤1: 使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需模块:
npm install mongoose
项目结构: 项目的结构将如下所示:
数据库结构:
目前数据库结构如下,我们还没有为数据库定义任何集合。
示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在userSchema上定义了模型。最后,我们使用model()方法创建了一个User模型,提供了模型名称、模式对象和数据库中的集合名称。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
const URI = "mongodb://localhost:27017/geeksforgeeks";
// Set Up the Database connection
mongoose.connect(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const userSchema = new mongoose.Schema({
name: String,
age: String,
city: String,
phone: Number,
gender: String
});
const User = mongoose.model('User', userSchema, 'User');
console.log(User);
程序运行步骤: 从项目的根目录中执行以下命令来运行应用程序:
node app.js
输出:
Model { User }
使用Robo3T GUI工具实现的数据库的GUI表示:
示例2: 在这个示例中,我们通过向model()方法传递模型名称和模式对象来说明model()方法的功能。
文件名:app.js
// Require mongoose module
const mongoose = require("mongoose");
const URI = "mongodb://localhost:27017/geeksforgeeks";
// Set Up the Database connection
const connectionObject = mongoose.createConnection(URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
const customerSchema = new mongoose.Schema({
name: String,
items: [],
amount: Number,
date: Date
});
const Customer =
connectionObject.model('Customer', customerSchema);
console.log(Customer);
运行程序的步骤:
从项目的根目录中执行以下命令来运行应用程序:
node app.js
输出:
Model { Customer }
使用Robo3T GUI工具的数据库的GUI表示:
参考: https://mongoosejs.com/docs/api/connection.html#connection_Connection-model