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();
Hey this is really very useful information.Thanks for sharing this post with us
ReplyDeleteNode JS Online training
Node JS training in Hyderabad
wow!!!very awesome one
ReplyDeleteFull Stack Training in Chennai | Certification | Online Training Course | Full Stack Training in Bangalore | Certification | Online Training Course | Full Stack Training in Hyderabad | Certification | Online Training Course | Full Stack Training in Pune | Certification | Online Training Course | Full Stack Training | Certification | Full Stack Online Training Course
most important and useful one thanks for shared this valuable one.
ReplyDeleteFull Stack Training in Chennai | Certification | Online Training Course | Full Stack Training in Bangalore | Certification | Online Training Course | Full Stack Training in Hyderabad | Certification | Online Training Course | Full Stack Training in Pune | Certification | Online Training Course | Full Stack Training | Certification | Full Stack Online Training Course