Mongoose Model.createCollection()函数
Mongoose API的Model.createCollection()方法用于为模型创建集合。默认情况下,Mongoose在数据库中不会为模型创建任何集合,直到创建了任何文档。createCollection()方法用于显式地创建集合。
设置Node.js应用程序:
步骤1: 使用以下命令创建一个Node.js应用程序:
npm init
步骤2: 创建NodeJS应用程序后,使用以下命令安装所需的模块:
npm install mongoose
项目结构: 项目的结构将如下所示:
示例1: 在这个示例中,我们使用mongoose建立了一个数据库连接,并在userSchema上定义了模型。最后,我们在User模型上创建了一个集合。
- 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
})
// Defining User schema
const userSchema = new mongoose.Schema(
{ name: String, age: Number }
)
// Defining User model
const User = mongoose.model('User', userSchema);
// Create collection of Model
User.createCollection().then(function (collection) {
console.log('Collection is created!');
});
运行程序的步骤: 从项目的根目录中执行以下命令来运行应用程序:
node app.js
输出:
1. 在控制台上执行:
Collection is created!
2. 您可以使用任何GUI工具以图形形式表示数据库。在这里,我使用了Robo3T GUI工具进行图形表示。
示例2: 在这个示例中,我们建立了一个数据库连接,并添加了一个回调函数,一旦数据库连接建立,它就会执行,并且定义了userSchema模型。最后,我们在User模型上创建了一个集合。
- app.js: 将下面的代码写入app.js文件中:
// Require the mongoose module
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Set Up the Database connection
mongoose.connect('mongodb://localhost:27017/geeksforgeeks', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then((result) => {
console.log('Connection Established')
}).catch((err) => {
console.log(err)
});
// Defining User schema
const userSchema = new Schema(
{ name: String, age: Number, email: String }
)
// Defining User model
const User = mongoose.model('User', userSchema);
// Create collection of Model
User.createCollection().then(function (collection) {
console.log('Collection is created!');
});
运行程序的步骤: 在项目的根目录下执行以下命令运行应用程序:
node app.js
输出:
1. 在控制台上:
Connection Established
Collection is created!
2. 您可以使用任何GUI工具以图形形式表示数据库。在这里,我使用了Robo3T GUI工具进行图形表示。
参考: https://mongoosejs.com/docs/api/model.html#model_Model-createCollection