简体   繁体   English

MongoDB使用Mongoose保存问题

[英]MongoDB using Mongoose save issues

I have some issues saving datas in my mongodb using mongoose. 我有一些问题使用mongoose在我的mongodb中保存数据。 Here is the code that i use : 这是我使用的代码:

////////////////////////////////////////
//// Mongoose test
var url = mongoUrl + dbCollectionName;

var mongoose = require('mongoose');
mongoose.connect(url);
var db = mongoose.connection;

db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function (callback) {
    console.log(getTimeStamp() + 'Connected to Mongo with Mongoose');
    insertDocuments(db);
});

var ackSchema = new mongoose.Schema({
    hostgroup : String,
    host : String,
    service : String,
    timePeriod : String,
    startTime : Number,
    ackTime : Number,
    deltaTime : Number,
    caseNumb : String,
    state : Number,
    author : String,
    ackId : Number,
    });

// Creation of the model document
var ackModel = mongoose.model(collectionName, ackSchema, collectionName);

//////////////////////////////////////
//// Functions

// MySQL function (query, push to array etc)
var mysqlQuery = function (callback) {
    var query = mysqlConnection.query(sqlQuery), sql = [];
    var anyRow = 0;
    // Log query error
    query.on('error', function (err) {
        if (err) {
            console.error(getTimeStamp() + 'Error in MySQL query: ' + err);
            return;
        }
    });

    // On result, push results in sql array
    query.on('result', function (row) {
        // Non-blocking I/O
        mysqlConnection.pause();
        mysqlConnection.resume();
        sql.push(row);
        callback(row);
    });

    // Information then close connection
    query.on('end', function (row) {
        // If anRow == 1, close the app.
        if (!row) { anyRow = 1; }
        if (row) { anyRow = 0; }

        if (anyRow == 1) {
            console.log(getTimeStamp() + 'Connection to Mongoose closed ');
            console.log(getTimeStamp() + 'Connection to MySQL closed ');
            process.exit(0);
        }
        if (anyRow == 0) {
            console.log(getTimeStamp() + 'Connection to Mongoose closed ');
            console.log(getTimeStamp() + 'Connection to MySQL closed ');
        }
    });
    mysqlConnection.end();
};               

// Insert Documents into mongodb using MySQL info and mongoose ackModel.
var insertDocuments = function(db) {
    // SQL Query to fetch row
    mysqlQuery(function (row) {
        //// IF 8/20
        if (row.timeperiod == timePeriod820) {
            returnValue = timePeriodCalc(row); // Function from timeperiod.js
            deltaValue = parseInt(returnValue.slice(6)); // Get our Delta Value
            caseValue = returnValue.slice(0,4); // Get the Case Number, verification purpose
        //// ELSE 24/7
        } else {
            deltaValue = (row.ack_time - row.start_time);
            caseValue = 'C.0';};
        };

        var ack = new ackModel({
            hostgroup : row.hostgroup,
            host : row.hostname,
            service : row.servicename,
            timePeriod : row.timeperiod,
            startTime : row.start_time,
            ackTime : row.ack_time,
            state : row.state,
            deltaTime : deltaValue,
            caseNumb : caseValue,
            author : row.author,
            ackId : row.ack_id});

        console.log(ack);       
        //console.log(getTimeStamp() + 'SAVE Mongoose : ' + ack.author + ' ' + ack.ackId);

        ack.save(function (err1, ack) {
            if (err1) {
                console.log(getTimeStamp() + 'Mongoose .save error : ' + err1);
            }
            else { 
                console.log(getTimeStamp() + 'SAVE Mongoose : ' + ack.author + ' ' + ack.ackId); 
            }
        });
    }); 
};  

This is what the log return : 这是日志返回的内容:

[2016-01-12 10:56:04.403] - Connected to Mongo with Mongoose
{ _id: 5694cdb49b274b1100262896,
  ackId: 1184,
  author: 'victor.b',
  caseNumb: 'C.10',
  deltaTime: -1200,
  state: 2,
  ackTime: 1452590840,
  startTime: 1452592040,
  timePeriod: 'RESSOURCES-GPE-N1-8/20',
  service: 'Service-Random-5M',
  host: 'CRI_HOST3',
  hostgroup: 'CRIDF' }
[2016-01-12 10:56:04.506] - Connection to Mongoose closed
[2016-01-12 10:56:04.507] - Connection to MySQL closed

So as you can see everything seems to be fine since my ack document from my ackModel is filled perfectly with the right informations. 因此,你可以看到一切似乎都很好,因为我的ackModel中的ack文档完全填充了正确的信息。 But the save didn't work. 但是保存不起作用。 I've tested a LOT of thing before coming here but i'm out of ideas. 在来到这里之前我已经测试了很多东西,但我没有想法。

EDIT 1 : Thanks to @zangw i've figured out that my problem is coming from this block of the code : 编辑1:感谢@zangw我发现我的问题来自这段代码:

// On result, push results in sql array
query.on('result', function (row) {
    // Non-blocking I/O
    mysqlConnection.pause();
    mysqlConnection.resume();
    sql.push(row);
    callback(row);
});

Since i'm not tottally used with node.js callbacks maybe i'm doing something wrong with the one in there. 因为我没有与node.js一起使用回调,也许我在那里做错了。

So the problem was from this part : 所以问题来自这部分:

    query.on('end', function (row) {
    // If anRow == 1, close the app.
    if (!row) { anyRow = 1; }
    if (row) { anyRow = 0; }
    if (anyRow == 1) {
        console.log(getTimeStamp() + 'Connection to MongoDB closed ');
        console.log(getTimeStamp() + 'Connection to MySQL closed ');
        process.exit(0);
    }
    if (anyRow == 0) {
        console.log(getTimeStamp() + 'Connection to MongoDB closed ');
        console.log(getTimeStamp() + 'Connection to MySQL closed ');
    }
});

So i've stopped usinf stream reading rows and changing the MySQLQuery and inserdocuments function into one simpler function : 所以我已停止使用流读取行并将MySQLQuery和inserdocuments函数更改为一个更简单的函数:

var insertDocuments = function() {
// Get the documents collection
var returnValue = 0,
    caseValue = "";
var test = 0;
var ackAllreadyExist = 0;

//var query = mysqlConnection.query(sqlQuery), sql = [];
var query = mysqlConnection.query(sqlQuery, function(err,row) {
    if(err) console.log('MySQL error : ' + err);
    for (var i=0; i<row.length; i++){
        //// IF 8/20
        if (row[i].timeperiod == timePeriod820) {
            returnValue = timePeriodCalc(row[i]); // Function from timeperiod.js
            deltaValue = parseInt(returnValue.slice(6)); // Get our Delta Value
            caseValue = returnValue.slice(0,4); // Get the Case Number, verification purpose
        //// ELSE 24/7
        } else {
            deltaValue = (row[i].ack_time - row[i].start_time);
            caseValue = 'C.0';
        };

        var ack = new ackModel({
            hostgroup : row[i].hostgroup,
            host : row[i].hostname,
            service : row[i].servicename,
            timePeriod : row[i].timeperiod,
            startTime : row[i].start_time,
            ackTime : row[i].ack_time,
            state : row[i].state,
            deltaTime : deltaValue,
            caseNumb : caseValue,
            author : row[i].author,
            ackId : row[i].ack_id});

        //console.log(row[i]);
        //console.log(ack);     
        //console.log(getTimeStamp() + 'SAVE Mongoose : ' + ack.author + ' ' + ack.ackId);

        ack.save(function (err,ack) {
            if (err) {
                console.log(getTimeStamp() + 'Mongoose .save error : ' + err);
            };
            console.log(getTimeStamp() + 'SAVE Mongoose : ' + ack.author + ' ' + ack.ackId); 
            test++;
            if(test == row.length) {
                mysqlConnection.end();
                console.log(getTimeStamp() + 'Connection to MongoDB closed ');
                console.log(getTimeStamp() + 'Connection to MySQL closed ');
                process.exit(0);
            };
        });
        if (debug == 1) { 
            console.log(getTimeStamp() + 'SAVE Mongoose : ' + ack.author + ' ' + ack.ackId); 
        };
    };
});
};

I'm not supposing to work like this in node.js i know but after 2 week on this problem (It's for my work, money !) I don't mind anymore. 我不想在我知道的node.js中这样工作,但是在这个问题2周后(这是我的工作,钱!)我不介意了。

Thanks @zangw for showing me the start of the answer. 谢谢@zangw向我展示了答案的开始。

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

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