【问题标题】:Cannot see a field added on a JSON document with Nodejs and Mongoose看不到使用 Nodejs 和 Mongoose 在 JSON 文档中添加的字段
【发布时间】:2016-04-23 18:58:41
【问题描述】:

如果我使用 mongoose 用这样的简单查询查询 MongoDB:

User
.find()
.where('address.loc').near({ center: [lat,lng], maxDistance: 1 })
.exec(function(err, result) {

  if (err) {
    request.log(['server', 'database', 'error'], 'An error occured during the execution of the query');
  }else{
    for(var i=0;i<result.length;++i){
      result[i]["distance"] = 5;
    }
    console.log(result[0].distance);
    console.log(result[0])
  }

});

第一个 console.log 打印:5

但第二个打印:

{ address: { loc: [ 37.0814402, 15.287517 ], value: 'viale tica' }, tags: [ 'Primi', 'Secondi' ], __v: 0, cap: 96100, ad_number: 15, business_email: 'prova@provbhifbvvyvg', _id: 571b3b78249a2e160b4eee3f }

为什么这个文档和结果数组中的其他文档没有字段距离?

【问题讨论】:

    标签: json node.js mongodb mongoose


    【解决方案1】:

    因为result[0] 是一个猫鼬文档对象。当您调用console.log(result[0]) 时,结果将转换为字符串(使用猫鼬文档toString 函数)。但猫鼬文档不包含distance 字段。

    要做你想做的事,你应该将每个文档转换为对象:

    var objects = results.forEach(results, function(res) {
      res = res.toObject();
      res["distance"] = 5;
      return res;
    });
    console.log(objects[0].distance);
    console.log(objects[0]);
    

    http://mongoosejs.com/docs/api.html#document_Document-toObject

    【讨论】:

    • 谢谢。我没想到猫鼬对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-01-04
    • 2014-07-20
    • 2021-12-08
    • 2020-02-23
    • 1970-01-01
    • 1970-01-01
    • 2023-02-14
    相关资源
    最近更新 更多