我想通过mongoose在我的节点服务器中保存一个mongodb文件:
mongoose.connect('mongodb://localhost/appJobs');
var db = mongoose.connection;
db.on('error', function() {console.log("error")});
db.once('open', function () {
console.log("connected!");
// init the schema
var jobSchema = mongoose.Schema({ bName: String , phone :Number ,location:[{longitude:Number,latitude:Number}],Email:String,field:String,exp:String});
var job = mongoose.model('jobs',jobSchema);
我的工作数据应来自该POST请求:
app.get('/postJob', function(req,res){
console.log("request method :" + req.method);
// Website you wish to allow to connect
res.setHeader('Access-Control-Allow-Origin', 'http://127.0.0.1:8020');
// Request methods you wish to allow
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
// Request headers you wish to allow
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
// Set to true if you need the website to include cookies in the requests sent
// to the API (e.g. in case you use sessions)
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Content-Type', 'application/json');
// Pass to next layer
console.log("Data :");
var postObject = url.parse(req.url,true).query;
//testing
console.log(postObject);
console.log(postObject.bname);
// creating and saving the posted job data to mongodb\jobs
var recJob = new job ({'bName':postObject.bname , 'phone' : postObject.bPhone ,'Email':postObject.bEmail ,'field':postObject.fieldSelected});
recJob.save(function(error,prod) {
if(error) {
console.log("error");
}
else {
console.log("a job was saved to mongodb");
}
});
res.send("OK!");
});
我得到的错误是:“ReferenceError:作业未定义”虽然我在服务器启动时定义。 postObject是我想要添加的数据的来源。
答案 0 :(得分:1)
如果您在定义app.get路由之前关闭db.once回调,我无法从您的帖子中看出来。 jobs
变量的作用域为db.once
回调的匿名函数。
Mongoose如果非常好,可以让你将模型定义分解为多个文件。在服务器引导程序中连接mongoose后,它是全局的,您可以将模型定义放在自己的文件中。