简体   繁体   English

数据未使用Mongoose保存在MongoDB中

[英]Data not saving in MongoDB using Mongoose

I am newbie in Nodejs world. 我是Nodejs世界的新手。 I am trying to insert data in MongoDB using Mongoose. 我正在尝试使用Mongoose在MongoDB中插入数据。 The idea is 这个想法是
- I will have a server running on node - any incoming POST data will be saved in Mongo. -我将在节点上运行服务器-任何传入的POST数据都将保存在Mongo中。

The problem when the below code is run no data gets saved in MongoDB and also no error is shown. 当运行以下代码时,没有数据保存在MongoDB中并且没有显示错误的问题。 Am i missing something here. 我在这里想念什么吗? Any help will be really appreciated. 任何帮助将不胜感激。

I have the below code that writes data in mongoDB for an incoming http request. 我有下面的代码在mongoDB中为传入的HTTP请求写入数据。

var http = require('http') // http module
, fs = require('fs')  // file system module
, qs = require('querystring') // querystring parser
, mongoose = require('mongoose'); 

mongoose.connect("mongodb://localhost/app_data_db");
var db = mongoose.connection;
var appDataSchema = new mongoose.Schema({

    record_id:      Number,
    app_version:    Number,
    imei:           String,
    created_time:   Date,
    device_uid:     String,
    model:          String
});

var appDataModel = mongoose.model("app_data_collection",appDataSchema);

var PORT=8080;

http.createServer(function(req,res){

if(req.method == "POST") {
    var POST = {};
    //parse query string
    req.on('data', function(data) {
        data = data.toString();
        data = data.split('&');
        for (var i = 0; i < data.length; i++) {
           var _data = data[i].split("=");
           POST[_data[0]] = _data[1];
        }

        db.once('open', function (callback) {
            appDataModel.create({
                  record_id:      POST["id"],
                  app_version:    POST["app_version"],
                  imei:           POST["imei"],
                  created_time:   new Date((parseInt(POST["created_time"]) + 19800) *1000), // to set correct time zone IST
                  device_uid:     POST["device_uid"],
                  model:          POST["model"]

                });
        });
        res.writeHead(200, {'Content-Type': 'text/plain'});
        res.end('saved to DB:'+POST["id"]+'\n');
        console.log('saved to DB:'+POST["id"]+'\n');
    });
    mongoose.disconnect();
}


}).listen(PORT);

To test this I am manually firing this curl call: 为了测试这一点,我手动触发了这个curl调用:

curl -X POST --data "id=58648148&app_version=4.8&imei=355886053224492&created_time=1417372202&device_uid=e385c8a5a4c01304&model=GT-I9082" http://localhost:8080

There are couple problems with your code: 您的代码有几个问题:

1) you call mongoose.disconnect outside of the callback, which means that it's called before the callback is executed 1)您在回调之外调用mongoose.disconnect ,这意味着在执行回调之前已调用它

2) you're creating the model inside the callback, but sending the response outside of it, so the response is sent before the model is created 2)您正在回调中创建模型,但在响应之外发送响应,因此响应在创建模型之前发送

3) and finally create method provides a callback when the entity is saved to the db, which you don't use it all 3)最后,当实体保存到数据库中时, create方法提供了一个回调,您无需全部使用它

Here's the modified code: 这是修改后的代码:

mongoose.connect("mongodb://localhost/app_data_db");
db.on('open', function() {
    http.createServer(function(req, res) {

        if(req.method == "POST") {
            var POST = {};
            //parse query string
            req.on('data', function(data) {
                data = data.toString();
                data = data.split('&');
                for (var i = 0; i < data.length; i++) {
                    var _data = data[i].split("=");
                    POST[_data[0]] = _data[1];
                }    

                appDataModel.create({
                  record_id:      POST["id"],
                  app_version:    POST["app_version"],
                  imei:           POST["imei"],
                  created_time:   new Date((parseInt(POST["created_time"]) + 19800) *1000), // to set correct time zone IST
                  device_uid:     POST["device_uid"],
                  model:          POST["model"]        
                }, 
                function(err){
                    res.writeHead(200, {'Content-Type': 'text/plain'});
                    res.end('saved to DB:'+POST["id"]+'\n');
                    console.log('saved to DB:'+POST["id"]+'\n');
                    mongoose.disconnect();
               });                    
           });    
        }        
    }).listen(PORT);
});

I think I got this working. 我想我已经做到了。 I have moved the mongoose connection inside. 我已经将猫鼬连接移到了里面。 Rest all is same. 休息都一样。 Since I wanted to post the code hence answering instead of commenting. 由于我想发布代码,因此回答而不是评论。 This may help others. 这可能会帮助其他人。 Here is the complete code 这是完整的代码

var http = require('http') // http module
    , fs = require('fs')  // file system module
    , qs = require('querystring') // querystring parser
    , mongoose = require('mongoose');

var appDataSchema = new mongoose.Schema({
         record_id: Number,
         app_version: Number,
         imei: String,
         created_time: Date,
         device_uid: String,
         model: String
    });

var appDataModel = mongoose.model("app_data_collection", appDataSchema);

var PORT = 8080;

http.createServer(function(req, res) {

    if (req.method == "POST") {

        var POST = {};
        //parse query string
        req.on('data', function(data) {
            data = data.toString();
            data = data.split('&');
            for (var i = 0; i < data.length; i++) {
                var _data = data[i].split("=");
                POST[_data[0]] = _data[1];
            }

            mongoose.connect("mongodb://localhost/app_data_db");
            var db = mongoose.connection;

            db.on('error', console.error.bind(console, 'connection error:'));

            db.once('open', function() {
                appDataModel.create({
                record_id: POST["id"],
                app_version: POST["app_version"],
                imei: POST["imei"],
                created_time: new Date((parseInt(POST["created_time"]) + 19800) * 1000), // to set correct time zone IST
                device_uid: POST["device_uid"],
                model: POST["model"]

            }, function(err) {
                res.writeHead(200, {'Content-Type': 'text/plain'});
                res.end('saved to DB:' + POST["id"] + '\n');
                console.log('saved to DB:' + POST["id"] + '\n');
                mongoose.disconnect();
            });
        });
    });
  }

}).listen(PORT);

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

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