创建用户的小应用程序,应用程序有2个文件(app.js)和业务逻辑文件(models / users.js),当您想要创建新用户时,会发生错误消息:
错误消息
var newuser = new userAA({
^
TypeError: userAA is not a function
at Object.<anonymous> (e:\2016\db-mongoose-seperat-file\db-MONGOOSE-seperate.js:25:15)
at Module._compile (module.js:409:26)
我的user.model.js
var mongoose=require('mongoose');
//schema
var userSchema =mongoose.Schema({
username:{
type:String,
index:true
},
password:{type:String},
email:{type:String},
name:{type:String}
});
// export model
module.exports=mongoose.model('usermodel',userSchema);
// export model methods
module.exports={
dummyfunc:function (){ console.log("Dummy func111111111"); },
dummyfunc2:function (){ console.log("Dummy func2222222"); },
};
我的app.js
var express=require('express');
var http= require('http');
var app=express();
var mongoose=require('mongoose');
// connect to db
mongoose.connect('localhost:27017/logindb2');
// include mongoose schema-model to app.js
var userAA=require('./models/users.models');
userAA.dummyfunc();
userAA.dummyfunc2();
// ERROR in the following line 'userAA' is not a function
var newuser = new userAA({
username:"Mr.Zombi",
password:"mJdmOdmn3k=34",
email:"eee@eskander.com",
name:"f.name"
});
app.get("/",function(req,res){
userAA.dummyfunc();
userAA.find({},function(err,docs){
console.log(docs);
res.send(docs);
});
});
http.createServer(app).listen(5000,function(){
console.log('Run db-MONGOOSE Server app');
});
答案 0 :(得分:0)
您正在使用module.exports两次。除去
module.exports={
dummyfunc:function (){ console.log("Dummy func111111111"); },
dummyfunc2:function (){ console.log("Dummy func2222222"); },
};
和
userAA.dummyfunc();
userAA.dummyfunc2();
会让它发挥作用。