Mongoose save()实际上没有保存

时间:2016-07-01 05:45:32

标签: node.js mongodb express mongoose save

我正在尝试找到我的记录,更新并保存。我可以看到更新的数据,它仍然可以在save()的回调中显示更新的数据。但是,当我进入数据库时​​,它实际上是更新:

Skills.findOne({ skillsCat: req.body.skillsCat }, (err, gets)=> {
  if (err) {
      res.send(err)
      return
  }

  if (gets && gets.skillName.indexOf(req.body.skillName) !== -1) {
    // Here I update my data
    gets.percent[gets.skillName.indexOf(req.body.skillName)] = req.body.percent
    Console.log(gets);   // Here I can see the data is updated

    return gets.save((err, updated)=> {
      Console.log(updated);   // Here I can see the data is updated
      if (err) { return }
      res.json({
        message: 'Skill updated successfully',
        data: updated
      })
    })

  } else {
    return
  }
})

之前是否有人遇到类似问题并帮助我解决这个问题?感谢。

1 个答案:

答案 0 :(得分:1)

尝试以下代码:

gets.percent[gets.skillName.indexOf(req.body.skillName)] = req.body.percent
Console.log(gets);   // Here I can see the data is updated

//Notice that 'fieldname' is the name of actual field in database
 gets.markModified('fieldname');

return gets.save((err, updated)=> {
  Console.log(updated);   // Here I can see the data is updated
  if (err) { return }
  res.json({
    message: 'Skill updated successfully',
    data: updated
  })
})