MongoDB基础操作及模块化

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


评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值