猫鼬.findByIdAndUpdate不更新记录

时间:2018-11-17 19:52:15

标签: mongoose

我有一条使用猫鼬的快速路线。该.findByIdAndUpdate无法正常工作。我看到“ removeId”进来了,第二个console.log显示了正确的记录...但是它没有更新!我在这里做错什么了吗?

router.post('/highlight', jsonParser, (req, res) => {
    const { removeId, addId } = req.body; 
    console.log('removeId', removeId)
    Article
        .findByIdAndUpdate(removeId, {
            featured: false
        })
        .then(updatedArticle => {
            console.log('updated article', updatedArticle)

2 个答案:

答案 0 :(得分:1)

这是一个奇怪的默认值,但是findByIdAndUpdate在默认情况下不会返回更新的记录。您必须通过{new:true}才能获得它。

router.post('/highlight', jsonParser, (req, res) => {
    const { removeId, addId } = req.body; 
    console.log('removeId', removeId)
    Article
        .findByIdAndUpdate(removeId,{new: true}, {
            featured: false
        })
        .then(updatedArticle => {
            console.log('updated article', updatedArticle)

答案 1 :(得分:0)

Mongodb findOneAndUpdate方法具有一个名为returnNewDocument的选项,根据documentation

  

可选。设置为true时,返回更新的文档,而不是   原始文件。默认为 false

猫鼬包装了该方法,但根据其code/documentation调用了通过选项new

outer.post('/highlight', jsonParser, (req, res) => {
  const { removeId, addId } = req.body; 
  console.log('removeId', removeId)
  return Article.findByIdAndUpdate(removeId, {featured: false}, {new: true})
    .then(updatedArticle =>
       console.log('updated article', updatedArticle)
    )   
})

也不要忘记您的发帖方法中的return Article.findByIdAndUpdate

相关问题