【问题标题】:updating mongoose json object doesn't seem to work更新 mongoose json 对象似乎不起作用
【发布时间】:2019-03-20 06:36:18
【问题描述】:

我没有收到任何错误或故障,但使用下面的架构,我似乎无法更新 fact1.nested1。

如果不使用嵌套的 Json 它可以工作,所以我设法通过使用更新nested1

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

但无论我尝试按照以下方式更新它都不会改变任何东西。我做了一些研究并尝试了大多数解决方案,猫鼬有什么变化吗? 是否有其他方法可以在不更改 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);
            });

【问题讨论】:

  • 我认为type: JSON 无效。 fact1 是 JSON 格式的字符串还是对象?
  • 嗨,在我的模式中它被称为 type: JSON 我认为它是一个有效的类型,我现在确实意识到根据添加的附件它提到了对象。所以 coinFactTransparent 是 fact1 而 coinbooltransparent 是 nested1。

标签: json mongoose nested


【解决方案1】:

这对我有用,我还按照以下方式调整了架构。此外,我相信添加更多参数而不仅仅是 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);
            });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-03
    • 2015-09-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多