在猫鼬模式的数组元素更新

问题描述 投票:0回答:1

我想在我的猫鼬架构更新snippets的一个元素。

我的猫鼬架构。

const Schema = new mongoose.Schema({
  // ...
  createdAt: Date,
  snippets: {} // here I push ['string..', ['array of strings..']]
})    

下面是snippets的指南针视图。

enter image description here

用下面的代码问题是,它完全擦除存储的其他元素,比它的工作原理等。无法指定我想更新片段[0],而不是整个事情..?

User.findOneAndUpdate({ username: req.session.user.username },
  { $set: { snippets: [snippet] } }, callback)

使用findOne andsave尝试,但它不会更新数据库。

const snippet = [req.body.code, [req.body.tags]]
User.findOne({ username: req.session.user.username }, function (err, fetchedUser) {
  if (err) console.log(err)
  fetchedUser.snippets[req.params.id] = snippet // should be set to new snippet?
  fetchedUser.save(function (err, updatedUser) {
    if (err) console.log(err)
    console.log('edited')
    // ...
  })
})

有什么建议么?

node.js mongodb mongoose
1个回答
0
投票

我以为我试过这个较早,但apparantly没有。

使用fetchedUser.markModified('snippets')解决了findOne / save实际上没有保存到数据库我的问题。

© www.soinside.com 2019 - 2024. All rights reserved.