【问题标题】:Javascript new object field not savedJavascript 新对象字段未保存
【发布时间】:2016-06-20 03:22:41
【问题描述】:

我正在使用 node.js 和 mongoose 根据查询获取一些数据。 Mongoose 函数 findOne 返回一个承诺,它给了我一个 javascript 对象。我想向该对象添加一个新字段并为其赋值,然后应用 stringify 函数。如果我打印我得到的字符串,我添加的新字段将不会被打印,即使我可以通过对象访问它。

model.findOne({},function (err, names) {})
         .then(function(data){
                    response.writeHead(200, {"Content-Type": "application/json"});
                    data['status'] = 200;
                    data['message'] = 'OK';
                    response.write(JSON.stringify(data));
                    response.end();
                },
                function(err) {
                    response.writeHead(500, {"Content-Type": "application/json"});
                    var execError = '{"status":500,"message":"'+ err.toString() +'"}';
                    response.write(execError);
                    response.end();
                }
        );

【问题讨论】:

    标签: javascript node.js mongodb mongoose


    【解决方案1】:

    我相信你在使用 lean() 方法,它允许你在查询链中返回一个纯 JavaScript 版本的结果文档。它适用于不创建完整模型实例的 Mongoose,然后您可以获取可以修改的完整 JavaScript 对象。因此将您的查询链更改为:

    var promise = model.findOne().lean();
    promise.then(function(data){
            response.writeHead(200, {"Content-Type": "application/json"});
            data['status'] = 200;
            data['message'] = 'OK';
            response.write(JSON.stringify(data));
            response.end();
        },
        function(err) {
            response.writeHead(500, {"Content-Type": "application/json"});
            var execError = '{"status":500,"message":"'+ err.toString() +'"}';
            response.write(execError);
            response.end();
        }
    );
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-22
      相关资源
      最近更新 更多