I want to save a mongodb document in my node server by mongoose :
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);
And my job data should come from that POST request :
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!");
});
The error i get is : "ReferenceError: job is not defined " although i defined at befor the server started . the postObject is the source of the data i want to add .
I can't tell from your post if you are closing out the db.once callback before you are defining the app.get route. The jobs
variable is scoped at the anonymous function for the db.once
callback.
Mongoose if very good about letting you break up your model definition into multiple files. Once you connect mongoose in your server bootstrapper, it's global and you can put your model definitions in their own file.