简体   繁体   中英

Require mongoose schema in JS file

This is my first time posting on StackOverflow, so please bear with me. I've been trying to use my mongoose schema inside another JS file to no avail. 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. However, when i try to 'require' it inside the JS file, my browser sends back the following error:

"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. 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:

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.

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

The ".js" is also optional, because your JavaScript file will automatically look for files of the same type.

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?).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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