简体   繁体   English

猫鼬不保存新文档

[英]Mongoose don't save new document

I want to save a mongodb document in my node server by mongoose : 我想通过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);

And my job data should come from that POST request : 我的工作数据应该来自该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!");


});

The error i get is : "ReferenceError: job is not defined " although i defined at befor the server started . 尽管我在启动服务器之前定义了错误,但我得到的错误是:“ ReferenceError:作业未定义”。 the postObject is the source of the data i want to add . postObject是我要添加的数据的来源。

I can't tell from your post if you are closing out the db.once callback before you are defining the app.get route. 我无法从您的帖子中得知在定义app.get路由之前是否要关闭db.once回调。 The jobs variable is scoped at the anonymous function for the db.once callback. jobs变量的作用域是db.once回调的匿名函数。

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. 一旦在服务器引导程序中连接了猫鼬,它就是全局的,您可以将模型定义放在它们自己的文件中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM