目录结构如下:
1.专门连接数据库的模块。
connectionDB.js
//定义一个用来连接MongoDB数据库的模块
const mongoose = require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/mytest', {useNewUrlParser: true, useUnifiedTopology: true})
mongoose.connection.once("open", () => {
console.log(`数据库已连接成功,MongoDB is running at:http://127.0.0.1:27017`)
})
2.创建模型对象的模块。
model.js
//该模块用来定义一个student模型
const mongoose = require('mongoose')
//定义Schema
const Schema = mongoose.Schema
const stuSchema = new Schema({
name: String,
age: Number,
gender: {
type: String,
default: "female"
},
address: String
});
//定义Model模型
const stuModel = mongoose.model('students', stuSchema);
module.exports = stuModel
3.主入口文件,用于调用模块的文件。
index.js
require("./modules/connectionDB")
const Student = require("./modules/model")
//测试
Student.find({}, (err, docs) => {
if (!err) {
console.log(docs)
}
})
网友评论