node.js - NodeJS/Mongoose: exports.function and module.exports incompatibility -


this user.js

    var mongoose = require('mongoose');     var bcrypt = require('bcrypt-nodejs');      var userschema = mongoose.schema({         email: {             type: string,             unique: true         },         password: string,     });      var user = mongoose.model('user', userschema);      function createdefaultusers() {         user.find({}).exec(function (err, collection) {             if (collection.length === 0) {                 user.create({                     email:  'name@eemail.com',                     password: 'password0',                 });     }      exports.createdefaultusers = createdefaultusers;     module.exports = mongoose.model('user', userschema); 

i call createdefaultusers in file create initial users.

but when gives me following error:

usermodel.createdefaultusers(); ^ typeerror: object function model(doc, fields, skipid) { if (!(this instanceof model)) return new model(doc, fields, skipid); model.call(this, doc, fields, skipid); } has no method 'createdefaultusers'

but if comment out module.exports = mongoose.model('user', userschema); compiles fine. doing wrong.

cheers.

in case, should attach function static method , export model.

var mongoose = require('mongoose'); var bcrypt = require('bcrypt-nodejs');  var userschema = mongoose.schema({     email: {         type: string,         unique: true     },     password: string, });  userschema.statics.createdefaultusers = function createdefaultusers(cb) {     return user.find({}).exec(function (err, collection) {         if (collection.length === 0) {             user.create({                 email:  'name@eemail.com',                 password: 'password0',             }, cb);         } else {             if (cb) {                  cb(err, collection);             }         }     }); };  var user = mongoose.model('user', userschema); module.exports = user; 

now can use directly model (which similar how you're using it):

require('./models/user').createdefaultusers(); 

Comments

Post a Comment

Popular posts from this blog

javascript - Using jquery append to add option values into a select element not working -

Android soft keyboard reverts to default keyboard on orientation change -

Rendering JButton to get the JCheckBox behavior in a JTable by using images does not update my table -