【问题标题】:Update field within nested array using mongoose使用猫鼬更新嵌套数组中的字段
【发布时间】:2018-09-13 06:59:27
【问题描述】:

我正在尝试更新数组中的子文档,但没有成功。新数据不会被保存。

快递:

router.put('/:id/:bookid', (req, res) => {
  library.findOneAndUpdate(
    { "_id": req.params.id, "books._id": req.params.bookid},
    { 
     "$set": {
        "title.$": 'new title'
      }
    }
}); 

LibraryScema:

const LibarySchema = new Library({
  Name: {
    type: String,
    required: false
  }, 
  books: [BookSchema]
});

bookScema:

const BookSchema = new Schema({

  title: {
    type: String,
    required: false
  },
  Chapters: [
    {
      chapterTitle: {
        type: String,
        required: false
      }
    }
  ]
});

我只打算更新子文档,而不是同时更新父文档和子文档。

【问题讨论】:

    标签: node.js express mongoose


    【解决方案1】:

    我遇到了类似的问题。我相信$set 在嵌套数组方面有问题(GitHub 上有一个完整的问题线程)。这就是我解决问题的方法。

    var p = req.params;
    var b = req.body;
    
    Account.findById(req.user._id, function (err, acc) {
        if (err) {
            console.log(err);
        } else {
            acc.websites.set(req.params._id, req.body.url); //This solved it for me
            acc.save((err, webs) => {
                if (err) {
                    console.log(err);
                } else {
                    console.log('all good');
                    res.redirect('/websites');
                }
            });
        }
    });
    

    我有一个嵌套数组的用户。

    试试这个代码

    router.put('/:id/:bookid', (req, res) => {
        library.findById(
            req.params.id, (err, obj) => {
                if (err) console.log(err); // Debugging
                obj.books.set(req.params.bookid, {
                    "title": 'new title',
                    'Chapters': 'your chapters array'
                });
                obj.save((err,obj)=>{
                    if(err) console.log(err); // Debugging
                    else {
                        console.log(obj); // See if the saved object is what expected;
                        res.redirect('...') // Do smth here
                    }
                })
            })
    });
    

    让我知道它是否有效,我会添加解释。

    解释:您首先要找到正确的对象(在本例中为library),然后在名为books 的数组中找到正确的对象。

    使用.set 将整个对象设置为新状态。您需要获取与以前的库对象实例没有变化的数据。

    我相信这种方式会覆盖并删除任何未传递到.set() 方法的数据。然后你save() 变了。

    【讨论】:

    • 我很难理解您的解决方案,因为我是 express/mongoose 的新手。您是否有机会编辑解决方案使其适用于我的案例?
    猜你喜欢
    • 1970-01-01
    • 2013-11-24
    • 1970-01-01
    • 1970-01-01
    • 2022-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-19
    相关资源
    最近更新 更多