简体   繁体   English

在JS文件中需要猫鼬模式

[英]Require mongoose schema in JS file

This is my first time posting on StackOverflow, so please bear with me. 这是我第一次在StackOverflow上发帖,所以请多多包涵。 I've been trying to use my mongoose schema inside another JS file to no avail. 我一直试图在另一个JS文件中使用我的猫鼬模式无济于事。 My directory looks like so: 我的目录如下所示:

/Project  
    /models
        model.js
    /views
        /admin
            foo.ejs  
    /public
        /js
            foo.js

My foo.ejs file uses the foo.js file, which requires the model. 我的foo.ejs文件使用foo.js文件,该文件需要模型。 However, when i try to 'require' it inside the JS file, my browser sends back the following error: 但是,当我尝试在JS文件中“要求”它时,我的浏览器会发回以下错误:

"Uncaught ReferenceError: require is not defined".  

I then tried to use 'browserify' but couldn't make it work either and don't know how else to proceed. 然后,我尝试使用'browserify',但也无法使其正常工作,也不知道该如何进行。 Please help and thanks in advance! 请帮助并提前致谢!

My model's code is: 我模型的代码是:

var mongoose = require("mongoose");

var categorySchema = new mongoose.Schema({
   name: String,
   series: [
      {
         type: mongoose.Schema.Types.ObjectId,
         ref: "Series"
      }
   ]
});

module.exports = mongoose.model("Category", categorySchema);

And inside my JS file, I try to require it like so: 在我的JS文件中,我尝试像这样要求它:

var Category = require("../../models/categoryMod");

Because your models.js file is exporting the schema, you don't need to require the name of the schema, just the name of the file. 因为您的models.js文件正在导出模式,所以您不需要输入模式名称,只需输入文件名称即可。

var Category = require('../../models/model.js'); var Category = require('../../ models / model.js');

The ".js" is also optional, because your JavaScript file will automatically look for files of the same type. “ .js”也是可选的,因为您的JavaScript文件将自动查找相同类型的文件。

If you're still having problems I'd make sure your version of node is up to date, and verify that your packages are properly installed. 如果您仍然遇到问题,请确保您的节点版本为最新,并确认软件包已正确安装。 (I assume you're using express?). (我假设您使用的是快递?)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM