【问题标题】:Object property is not getting assigned in the result of mongoose对象属性未在猫鼬的结果中分配
【发布时间】:2018-09-23 17:04:43
【问题描述】:

我已经执行了一个猫鼬查找查询并将结果存储在对象中。

var enabledPlayerQuery = playerCollection.find({playerMobile:{$gt:0}})

然后在那个对象上,我已经完成了这样的 exec 操作,以在每个对象中添加一个总硬币的价值,但在控制台上,当我用来打印对象时,它显示该值没有被分配。对象保持之前的状态。

enabledPlayerQuery.exec(function(err,queryResult){ 
    async.each(queryResult, function(users ,result){
        user.totalCoins = 1000;
    }, function(err){
        //anything console
    })
}

但是总硬币价值没有被分配。

我尝试使用 _.extend 方法来扩展这两个对象。还创建了另一个对象并将前一个对象的属性粘贴到该对象上,然后它也不起作用。

【问题讨论】:

标签: javascript node.js mongodb mongoose


【解决方案1】:

mongoose 查找查询返回的是一个 mongoose 对象,而不是 JS 对象。因此,您不能为 playerCollection 模型的猫鼬模式中未定义的返回对象分配键。为此,您需要在查找查询本身中使用 lean() 将此 mongoose 文档转换为 JS 对象:

var enabledPlayerQuery = playerCollection.find({playerMobile:{$gt:0}}).lean()

或者在结果对象上使用toObject()。

enabledPlayerQuery.exec(function(err,queryResult){ 
    async.each(queryResult, function(users ,result){
        user.toObject()
        user.totalCoins = 1000;
    }, function(err){
        //anything console
    })
}

【讨论】:

    【解决方案2】:

    在这种情况下尝试使用.lean()。它将为您提供一个简单的对象,您可以在其中利用对象操作的功能。

    var enabledPlayerQuery = playerCollection.find({playerMobile:{$gt:0}}).lean()
    

    原始输出保留了您用于从集合中获取值的架构格式。

    【讨论】:

      猜你喜欢
      • 2012-11-02
      • 2017-10-23
      • 2021-04-14
      • 2018-06-12
      • 2018-08-22
      • 2019-12-30
      • 1970-01-01
      • 2016-06-12
      • 2016-03-20
      相关资源
      最近更新 更多