MongoDB基础操作及模块化
文件结构
数据库的连接
db文件下的index.js
// 引入mongoose
const mongoose = require("mongoose")
// 将数据库连接暴露出去
module.exports = new Promise((resolve, reject) => {
mongoose.set("useCreateIndex", true) //解决第三个
// 连接数据库
mongoose
.connect("mongodb://localhost:27017/atguigu_movie", {
useNewUrlParser: true,
useUnifiedTopology: true,
}) //解决第一个和第二个
.then(() => resolve("数据库连接成功"))
.catch(() => reject("数据库连接失败"))
})
模型对象
model文件下的各个模型对象,例如一个Theaters.js文件
const mongoose = require("mongoose")
//创建约束对象
const theatersSchema = new mongoose.Schema({
title: String,
rating: Number,
runtime: String,
directors: String,
casts: String,
image: String,
doubanId: {
type: Number,
unique: true,
},
genre: [String],
summary: String,
releaseDate: String,
posterKey: String, //图片上传到七牛中,返回的key值
createTime: {
type: Date,
default: Date.now(),
},
})
//创建模型对象
const Theaters = mongoose.model("Theaters", theatersSchema)
//暴露出去
module.exports = Theaters