简体   繁体   中英

NodeJS/Mongoose: exports.function and module.exports incompatibility

This is my 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 another file to create initial users.

But when this gives me the 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 I comment out module.exports = mongoose.model('User', UserSchema); it compiles fine. What am I doing wrong.

Cheers.

In this case, you should attach that function as a static method and export the 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 you can use it directly from the model (which is likely very similar to how you're already using it):

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

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