javascript - 需要模型的 Mongoose 错误

标签 javascript node.js mongodb express mongoose

我对 NodeJS、require 和 mongoose 有一个相当奇怪的问题。 我为这样的用户模型创建了一个架构:

let mongoose = require('mongoose');
let Schema = mongoose.Schema;

let depositSchema = new Schema({
    customer: String,
    tyres : {
        amount: { type: Number, min: 1, required : true},
        tyreType : { type: String, required : true }
    },
    created : {
        at : { type: Date, default : Date.now },
        by : { type : Schema.ObjectId }
    },
    last_modified : {
        at : { type: Date },
        by : { type: Schema.ObjectId }
    },
    located_at : {
        column: { type: String, required : true },
        row: { type: String, required : true }
    }
});

depositSchema.pre('save', function(next) {
    let date = new Date();

    this.last_modified.at = date;

    if(!this.created.at) {
        this.created.at = date;
    }

    next();
});

module.exports = mongoose.model('Deposit', depositSchema);

所以你可以看到文件导出了mongoose模型。 如果我需要在另一个文件中使用此文件,如下所示:

let Deposit = require('../../models/deposit);

一切都很好。一切正常,我在使用模型并从中创建对象以将其保存在 Mongo 中时没有任何问题。

但是如果我需要这样的模型:

let Deposit = require('../../models/Deposit);

我从 Mongo 收到此错误:

    /app/node_modules/mongoose/lib/index.js:376
      throw new mongoose.Error.OverwriteModelError(name);
      ^
MongooseError: Cannot overwrite `Deposit` model once compiled.

错误点位于我需要模型的行。

我用 require 搜索了类似的问题,但没有找到任何有用的东西来解释我的问题。 另一个模型也会出现同样的问题,但拼写方向不同。 我很困扰。也许有人遇到了同样的问题,或者能够解释发生了什么以及导致问题的原因。

提前谢谢您。

祝大家度过成功的一周。

最佳答案

 var  mongoose = require('mongoose');
 let Deposit = mongoose.model('Deposit');

改用上面两行:let Deposit = require('../../models/deposit');

关于javascript - 需要模型的 Mongoose 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42386003/

相关文章:

javascript - 将带有类 ID 和图像的 div 添加到容器

javascript - 旋转表格中的图像

javascript - 如何避免使用 typescript 生成的表单中的换行?

node.js - Azure webapp node.js 应用程序未启动

mongodb - 使用 Jest 测试具有数据库调用的函数

ruby-on-rails - 使用 Rails 搜索 MongoDB

javascript - 使用 Ajax 从维基百科返回数据?

node.js - Hapi.js 无法读取 null 的属性 'statusCode'

javascript - 尝试从我的 mongoDB 访问数据并推送到 HTML 中的 <table>

javascript - 无法在 localhost 上启动 Node.js 的 MongoDB