简体   繁体   中英

when using mongoose.model() getting error TypeError: Cannot read property 'test' of undefined

Here is my schema

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

var test = new Schema({
    name : {
       type : String,
       require : true,
       sparse : true
    },
    description : {
       type : String
    },
    questions : {
       type : [Schema.Types.ObjectId],
       sparse : true
    }  }); 
    module.exports = new mongoose.model('test', test);

When I try to execute, it give me error as follows :

TypeError: Cannot read property 'test' of undefined
at new Mongoose.model (/home/utkarsh/Desktop/MEAN_REST_user_management/node_modules/mongoose/lib/index.js:329:25)
at Object.<anonymous> (/home/utkarsh/Desktop/MEAN_REST_user_management/app/models/test.js:19:18)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)
at require (internal/module.js:20:19)
at Object.<anonymous> (/home/utkarsh/Desktop/MEAN_REST_user_management/app/routes/test.js:6:13)
at Module._compile (module.js:541:32)
at Object.Module._extensions..js (module.js:550:10)
at Module.load (module.js:458:32)
at tryModuleLoad (module.js:417:12)
at Function.Module._load (module.js:409:3)
at Module.require (module.js:468:17)

I have used the same format earlier, it worked fine. Dont know why its not working. Can anyone help?

Change this:

module.exports = new mongoose.model('test', test);

To this:

module.exports = mongoose.model('test', test);

mongoose.model() isn't a class, so you shouldn't instantiate it (using new ).

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