2016-11-21 1 views
0

내 데이터베이스에 json 개체를 저장하려고합니다. save() 함수는 호출되지 않지만 json 객체는 절대로 저장되지 않습니다. 문제를 파악하는 데 도움이됩니다. 몽구스와의 연결 문제 일 것 같습니다. 여기 내 코드는 ...몽구스 스키마 개체에서 save() 콜백이 호출되지 않습니다.

var config = require('../config'); 
    var user = require('../user'); 
api.post('/addUser',function(req,res) { 
    var userID; 
    //creating a sample user under Model collection User.. so this becomes a document!! 
    console.log("addition of new user api hit!!"); 
    //sending a query to retrieve the no of users served 
    MongoClient.connect(dbURL, function (err, db) { 
     var UserCountCursor = db.collection("ourusers").find({"docName": "userCount"}).limit(1); 

     UserCountCursor.each(function (err, doc) { 
      if (err) 
       console.log("did not get the count"); 
      else 
      // var countString= JSON.stringify(doc); 
      //var docJson=JSON.parse(countString); 
       console.log("the json content is:" + doc.iparkoUserCount); 

      //increase the user count by 1 in the db. 
      var incCount = parseInt(doc.iparkoUserCount) + 1; 
      console.log("no of userrs:" + incCount); 
      // making an userId 
      userID = "ipkoID_C" + incCount.toString(); 
      //updating using MOngoClient 
      db.collection("ourusers").update({"docName": "userCount"}, {$set: {"iparkoUserCount": incCount}}); 
      console.log("the user count in the db has been updated!!"); 
      console.log("generated id for this guy is:" + userID); 

      if (userID != null) { 
       console.log("calling the save function"); 
       //closing the mongoclient connection 
       db.close(); 
       signUpUser(userID); 
      } 
     }); 
    }); 


    function signUpUser(userIDD) { 
     var me = new user({ 
      name: req.body.new_name, 
      password: req.body.new_pswd, 
      username: req.body.new_username, 
      phno: req.body.new_phn, 
      userId: userIDD 
     }); 

     console.log("the obj ::" + JSON.stringify(me)); 
     console.log("obj created and ready to be stored"); 
//connecting to the db using mongoose 
     mongoose.connect(config.database, function (err) { 
      if (err) 
       console.log("The error is :"+err); 
      else { 
       console.log("WE ARE CONNECTED USING MONGOOSE"); 
       //saving the sample user document 
       me.save(function (err) { 
        console.log("in the save func"); 
        if (err) throw err; 
        else { 
         console.log('User saved Successfully!!!!!'); 
         res.json({ 
          'whatStatus': 'user saved in the database!!', 
          'userID': userIDD 
         }); 
         mongoose.connection.close(); 
        } 
       }); 
      } 
     }); 
    } 
}); 

내 콘솔 로그 ::

addition of new user api hit!! the json content is:143 no of userrs:144 the user count in the db has been updated!! generated id for this guy is:ipkoID_C144 calling the save function the obj ::{"name":"Abhi","password":"jio","username":"abhijio","phno":"45142545","userId":"ipkoID_C144","_id":"583295bfa0f9f8342035d3b9"} obj created and ready to be stored C:\Users\shivendra\WebstormProjects\iParko\node_modules\mongodb\lib\utils.js:98 process.nextTick(function() { throw err; }); ^

형식 오류 : \ 사용자 \ shivendra \ WebstormProjects \ iParko \ 경로 : C에서 널 (null) 의 특성 'iparkoUserCount'을 읽을 수 없습니다 (C : \ Users \ shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb \ lib \ utils.js : 96 : 12) C : \ Users \ shivendra \ WebstormProjects \ iParko \ RegisteredParkingLots.js : 76 : 57 at handleCallback node_modules \ mongodb \ lib \ cursor.js : 742 : 16 at handleCallback (C : \ Users \ shivendra \ W) handleCallback (C : \ Users \ shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb \ lib \ cursor.js : 676 : 5 )에서 을 입력하십시오. (C : \ Users \ shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb \ node_modules \ 156)에 을 입력합니다. (C : \ Users \ shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb \ node_modules \ mongodb-core \ lib \ cursor.js : 588 : 12) (C : \ Users \ shivendra)에있는 의 C : \ Users \ shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb \ node_modules \ mongodb-core \ lib \ cursor.js : 681 : 3) \ WebstormProjects \ iParko \ node_modules \ mongodb \ lib \ cursor.js : 673 : 8)(C : \ Users \ shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb \ lib \ cursor.js : 262 : 12) at _each (C : \ Users \ shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb \ handleCallback (C : \ Users \ shivendra \ WebstormProjects \ iParko)에서 C : \ Users \ shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb \ lib \ cursor.js : 746 : 7 의 C : \ Users \ shivendra \ WebstormProjects \ iParko \ node_modules \ mongodb \ lib \ cursor.js : 676 : 5 handleCallback (C : \ Users \ mongodb \ lib \ utils.js : 96 : 12) shivendra \ WebstormProjects \ iParko \ node_modules \ MongoDB를 \ node_modules \ MongoDB의 핵심 \ lib 디렉토리 \ cursor.js : 156 : 5)

프로세스 종료 코드 완료 한

,

답변

0

mongoose.connect으로 db 연결을 두 번 열고 mongoose.connection.open()을 사용하여 db 연결을 여는 것처럼 보입니다. 그래서 당신은 오류가 발생합니다.

다음과 같이 하나의 연결로이 기능을 사용해보십시오. 당신의 UserCountCursor.each(...) 루프 내부

mongoose.connect(config.database, function(err, db) { 
      //var dbcon=mongoose.connection.open(); 

      //dbcon.on('error',function(){console.log('connction error:')}); 
      //dbcon.once('open',function(){ 
    if(err) { 
     console.log(err); 
    } else { 
       console.log("WE ARE CONNECTED USING MONGOOSE"); 
       //saving the sample user document 
       me.save(function (err) { 
        console.log("in the save func"); 
        if (err) throw err; 
        else { 
         console.log('User saved Successfully!!!!!'); 
         res.json({ 
          'whatStatus': 'user saved in the database!!', 
          'userID': userIDD 
         }); 
         //mongoose.connection.close(); 
        } 
       }); 
      } 
    }); 
+0

Aruna 나는 이것을 시도했지만 여전히 save() 기능을 사용하지 못하고있다. 나는 콘솔 로그뿐만 아니라 질문에 내 코드를 업데이 트했습니다 .. 좀 봐 줄 수 있습니다 .. - 도움을 주셔서 감사합니다 –

+0

@ Shiven_codeboy 오류가 있습니까? – Aruna

+0

오류는''null '의'iparkoUserCount '속성을 읽을 수 없습니다. 이 오류를 확인할 수 있습니까? – Aruna

0

, err 확인 후 당신은 또한 doc 확인해야합니다.그래서 당신이이 여기서

UserCountCursor.each(function (err, doc) { 
    if (err) 
    console.log("did not get the count"); 
    else 

    // var countString= JSON.stringify(doc); 

    //... 

}) 

대신 이렇게 :

UserCountCursor.each(function (err, doc) { 
    if (err){ 
    console.log("did not get the count"); 
    }else if(doc){ 

    // var countString= JSON.stringify(doc); 

    //... 

    } 

}) 

그런 다음 당신은 Cannot read property 'iparkoUserCount' of null 오류를 방지하고 당신은 당신의 save() 함수로 얻을 수 있습니다.

+0

고맙습니다 스티븐 !! 그게 진짜로 .. 그게 쉬웠어요. 모든 도움을 위해 고맙습니다. –

관련 문제