节点/ Express /猫鼬:尝试在MongoDB中设置嵌入文档,“一旦编译就无法覆盖'###'模型”

时间:2020-03-03 03:16:53

标签: node.js mongodb express mongoose

我正在尝试使用快递和猫鼬为Node中的模拟“租赁”业务设置路由。

到目前为止,我的后端工作良好,因为我可以将客户,电影等保存在数据库中。 但是,当我尝试连接出租路由时,会出现此错误:

消息:“一旦编译就无法覆盖Customer模型。”,

我相信问题是由于我试图将客户数据嵌入租赁文件中,但我不确定。

问题代码:

const { Rental, validateRental } = require("../Models/rental");
const { Movies } = require("../Models/movie");
const { Customers } = require("../Models/customer");
const express = require("express");
const router = express.Router();

////////////////////
//! [C]-RUD
////////////////////

router.post("/", async (req, res) => {
  const { error } = validateRental(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  const customer = await Customers.findById(req.body.customerId);
  if (!customer) return res.status(400).send("Invalid customer.");

  const movie = await Movies.findById(req.body.movieId);
  if (!movie) return res.status(400).send("Invalid movie.");

  if (movie.numberInStock === 0)
    return res.status(400).send("Movie not in stock.");

  let rental = new Rental({
    renter: {
      _id: customer._id,
      name: customer.name,
      phone: customer.phone
    },
    movie: {
      _id: movie._id,
      title: movie.title,
      dailyRentalRate: movie.dailyRentalRate
    }
  });
  rental = await rental.save();

  movie.numberInStock--;
  movie.save();

  res.send(rental);
});

////////////////////////
//! Exports
////////////////////////
module.exports = router;

我的Rentals猫鼬模型如下:

const Rentals = mongoose.model(
  "Rental",
  new mongoose.Schema({
    renter: {
      type: new mongoose.Schema({
        name: {
          type: String,
          required: true,
          minlength: 5,
          maxlength: 50
        },
        isGold: {
          type: Boolean,
          default: false
        },
        phone: {
          type: String,
          required: true,
          minlength: 5,
          maxlength: 50
        }
      }),
      required: true
    },
    movie: {
      type: new mongoose.Schema({
        title: {
          type: String,
          required: true,
          trim: true,
          minlength: 5,
          maxlength: 255
        },
        dailyRentalRate: {
          type: Number,
          required: true,
          min: 0,
          max: 255
        }
      }),
      required: true
    },
    dateOut: {
      type: Date,
      required: true,
      default: Date.now
    },
    dateReturned: {
      type: Date
    },
    rentalFee: {
      type: Number,
      min: 0
    }
  })
); 

最后,我的customer.js看起来像这样:

const mongoose = require("mongoose");
const Joi = require("@hapi/joi");
const CustomJoi = Joi.extend(require("joi-phone-number"));

// * ----------  PRE VALIDATE CUSTOMER NAME and PHONE NUMBER ----------
function validateCustomer(customer) {
  const schema = CustomJoi.object({
    name: CustomJoi.string()
      .min(2)
      .max(30)
      .trim()
      .required(),
    phone: CustomJoi.string()
      .phoneNumber({ defaultCountry: "US", strict: true })
      .trim()
      .required(),
    isGold: CustomJoi.boolean()
  });

  return schema.validate(customer);
}

const customerSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true,
    minlength: 2,
    maxlength: 30,
    trim: true
  },
  phone: {
    type: String,
    required: true,
    trim: true,
    minlength: 5,
    maxlength: 50
  },
  isGold: {
    type: Boolean,
    default: false
  }
});

//* Define customers model (moved the schema declaration into it.)
const Customers = mongoose.model("Customer", customerSchema);

exports.Customers = Customers;
exports.validate = validateCustomer;

1 个答案:

答案 0 :(得分:0)

好了,经过一天的测试,看起来我最终通过将整个模型声明放在try / catch中使用的答案似乎可以解决问题,并且没有明显的副作用。 我还没有进行性能分析,但是那超出了本教程的范围,以后我会解决。

let Customers;
 try { Customers = mongoose.model("Customer");
 } catch (error) {
 Customers = mongoose.model("Customer", customerSchema);
 }