[英]NodeJS/Mongoose: exports.function and module.exports incompatibility
This is my User.js 这是我的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. 我在另一个文件中调用createDefaultUsers以创建初始用户。
But when this gives me the following error: 但是,这给了我以下错误:
userModel.createDefaultUsers();
userModel.createDefaultUsers(); ^ TypeError: Object function model(doc, fields, skipId) { if (!(this instanceof model)) return new model(doc, fields, skipId);
^ TypeError:对象函数模型(文档,字段,skipId){如果(!(此模型实例))返回新模型(文档,字段,skipId); Model.call(this, doc, fields, skipId);
Model.call(this,doc,fields,skipId); } has no method 'createDefaultUsers'
}没有方法'createDefaultUsers'
But if I comment out module.exports = mongoose.model('User', UserSchema);
但是如果我注释掉
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();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.