代码之家  ›  专栏  ›  技术社区  ›  oudekaas

更新Mongoose JSON对象似乎不起作用

  •  0
  • oudekaas  · 技术社区  · 7 年前

    我没有得到任何错误或错误,但是通过下面的模式,我似乎无法更新fact1.nested1。

    如果不使用嵌套的JSON,它会起作用,因此我通过使用

    $set: {'nested1': req.body.newNested1}
    

    但是无论我按照下面的方法更新什么,都不会改变任何东西。我做了一些研究,尝试了大多数解决方案,Mongoose有什么变化吗? 是否有其他方法可以在不更改JSON中所有其他数据的情况下更新嵌套JSON。

    var mongooseSchema  = new Schema ({
    fact1: {
        type: JSON,
        minlength: 1,
        maxlength: 300,
        required: true,
        default: "emptyType"
    }})
    
        var setObj = {
        $set: {'fact1.nested1' : req.body.newNested1}
      }
        User.FactCheck.findByIdAndUpdate(id,{ 
                 setObj}
                , {
                    upsert: true,
                    'new': true
                }).exec(function(err, doc) {
    
    
                    if (err) return res.send(500, {
                        error: err
                    });
    
                    console.log (doc)
                    return res.send(doc);
                });
    

    enter image description here

    1 回复  |  直到 7 年前
        1
  •  0
  •   oudekaas    7 年前

    这对我来说是可行的,我也按照下面的内容改编了这个模式。另外,我相信添加更多的参数而不仅仅是setobj(例如(id,setobj,anotherparam)可能是它不能工作的原因,因为这是我最后更改的。 即使没有错误,也没有别的对我有用。

         var mongooseSchema  = new Schema ({
         fact1: {
            nested1: Boolean,
            nested2: String     
         }})
    
    
        objForUpdate.fact1 = {}
        objForUpdate.fact1 = {  'nested1' : req.body.newnested1,
          'nested2' : req.body.newnested2}
    
        User.SCHEMAPLAYER.findByIdAndUpdate(id,setObj
                , {
                    upsert: true,
                    'new': true
                }).exec(function(err, doc) {
    
    
                    if (err) return res.send(500, {
                        error: err
                    });
    
                    console.log (doc)
                    return res.send(doc);
                });