使用节点js添加mongodb数据值

时间:2016-07-14 05:54:10

标签: javascript node.js mongodb

大家好我需要使用node js从MongoDB添加一个集合的两个字段值{type:Number} 并将结果存储在MongoDB的同一集合中

第一个节点js查询从我的控制器内的MongoDB中获取数据值。 第二次尝试添加获取的值。 3rd使用节点js将结果存储在MongoDB的同一集合中。

1)。节点js

var levelScoreQuiz = require('../models/levelscoreSchema.js');
try{


         var queryObj = {};
         var projection = '-id child.quiz_level.score_pre';
         var projection2 = '-id child.quiz_level.score_curr'; 


         var a = levelScoreQuiz.findOne(queryObj,projection);
         var b = levelScoreQuiz.findOne(queryObj,projection2);
         //console.log(a);
         //console.log(b);
         var add = a + b;
         //console.log(add);
         res.send(add);


        var userObj = {

        level_pre:req.params.add


        };

        var user = new levelScoreQuiz(userObj);
        user.save(function(err, result){
            if (err) {
                console.log('Error While Saving the reuslt ' +err)}
        else{
            //console.log("User score saved successfully");
            console.log("User Previous score saved successfully");
            res.json(result);
        }
      });

    }catch(err){
        console.log('Error While Saving the reuslt ' +err);
        return next(err);
    }

2)。 MongoDB架构

var userScore = new Schema({

child: {

    quiz_level:{
        current_level:{type:Number},

            score_pre:{type:Number},
            score_curr:{type:Number}
    }
  }

});

3)。结果:它在浏览器中显示我的对象

 "[object Object][object Object]"

1 个答案:

答案 0 :(得分:0)

    var levelScoreQuiz = require('../models/levelscoreSchema.js');
try{


         var queryObj = {};
         var projection = {id: 0, 'child.quiz_level.score_pre': 1};
         var projection2 = {id: 0, 'child.quiz_level.score_curr': 1}; 


         var a = levelScoreQuiz.findOne(queryObj,projection);
         var b = levelScoreQuiz.findOne(queryObj,projection2);
         //console.log(a);
         //console.log(b);
         var add = a.child.quiz_level.score_pre + 
                   b.child.quiz_level.score_curr;
         //console.log(add);
         res.send(add);


        var userObj = {

        child: {quiz_level: { score_pre: req.params.add}}


        };

        var user = new levelScoreQuiz(userObj);
        user.save(function(err, result){
            if (err) {
                console.log('Error While Saving the reuslt ' +err)}
        else{
            //console.log("User score saved successfully");
            console.log("User Previous score saved successfully");
            res.json(result);
        }
      });

    }catch(err){
        console.log('Error While Saving the reuslt ' +err);
        return next(err);
    }