【问题标题】:update existing JSON property value based on MongoDB Results in NodeJS根据 NodeJS 中的 MongoDB 结果更新现有 JSON 属性值
【发布时间】:2018-02-08 12:12:19
【问题描述】:

我有一个像下面这样的 JSON

            var outputJson = [
                {
                    'Product' : 'TV',
                    'isSelected': 0
                },
                {
                    'Product' : 'Radio',
                    'isSelected': 0
                },
                {
                    'Product' : 'Book',
                    'isSelected': 0
                },                      
                {
                    'Product' : 'Watch',
                    'isSelected': 0
                }                 
            ]

现在我的目标是查找用户在 MongoDB 中是否有任何此类产品,如果是,则我想将 isSelected 值从“0”更新为“1”。我该怎么做,下面是我想要做的,但我的 JSON 没有更新

            outputJson.forEach(function(key,value){
                wishlistData.find({userID:req.user.id}, function(err,data{
                    data.forEach(function(k,i){
                        if (data[i].product=== outputJson[value].Product){
                            outputJson[value].isSelected = 1
                        }
                    })
                }); 
            });

【问题讨论】:

  • 使用 $in 选择用户并使用 $inc 更新参数

标签: jquery json node.js mongodb


【解决方案1】:

通过使用 Promise,我的问题得到了解决

Promise.all(outputJson.map(function(i,k) {
  return wishlistData.findOne({userID: req.user.id, product: i.Product}).then(function(data, err) {
    if (data !== null) { // if it actually found a match
      i.isSelected = 1;
    }
  });
})).then(function() {
    console.log(outputJson);
});

【讨论】:

    猜你喜欢
    • 2019-08-28
    • 1970-01-01
    • 2018-11-24
    • 2017-03-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-29
    • 1970-01-01
    相关资源
    最近更新 更多