MongooseError:Model.findOneAndUpdate()不再接受回调

tnkciper  于 2023-06-23  发布在  Go
关注(0)|答案(1)|浏览(126)

我在设置 Mongoose 时遇到了一个问题。
我的准则

export const getOne = (req, res) => {
    try {
        const postId = req.params.id

        PostModel.findOneAndUpdate(
            {
                _id: postId,
            },
            {
                $inc: { viewsCount: 1 },
            },
            {
                returnDocument: 'after',
            },
            (err, doc) => {
                if (err) {
                    console.log(error)
                    return res.status(500).json({ message: "cant return post" })
                }

                if (!doc) {
                    return res.status(404).json({
                        message: "post not found"
                    })
                }

                res.json(doc)
            },
        )
    } catch (error) {
        console.log(error)
        res.status(500).json({ message: "cant retunr post" })
    }
}

错误:
MongooseError:模特findOneAndUpdate()不再接受Function的回调。模特findOneAndUpdate(C:\Users\Kous\Desktop\First-Full-Stack\node_modules\mongoose\lib\model. js:二三九八:11)at getOne(file:///C:/Users/Kous/Desktop/First-Full-Stack/controllers/PostController.js:40:13)at Layer. handle [as handle_request](C:\Users\Kous\Desktop\First-Full-Stack\node_modules\express\lib\router\layer。js:九十五:5)在下一个(C:\Users\Kous\Desktop\First-Full-Stack\node_modules\express\lib\router\route。js:一百四十四:(13)路。派遣(C:\Users\Kous\Desktop\First-Full-Stack\node_modules\express\lib\router\route。js:一百一十四:(3)在层。handle [as handle_request](C:\Users\Kous\Desktop\First-Full-Stack\node_modules\express\lib\router\layer。js:九十五:5)在C:\Users\Kous\Desktop\First-Full-Stack\node_modules\express\lib\router\index。js:二百八十四:15参数(C:\Users\Kous\Desktop\First-Full-Stack\node_modules\express\lib\router\index。js:三百六十五:14)at param(C:\Users\Kous\Desktop\First-Full-Stack\node_modules\express\lib\router\index。js:三百七十六:(14)功能。process_params(C:\Users\Kous\Desktop\First-Full-Stack\node_modules\express\lib\router\index。js:421:3)

4sup72z8

4sup72z81#

export const getOne = async (req, res) => {
  try {
    const postId = req.params.id;

  PostModel.findOneAndUpdate(
  {
    _id: postId,
  },
  {
    $inc: { viewsCount: 1 },
  },
  {
    returnDocument: "after",
  }
).then((doc, err) => {
  if (err) {
    console.log(err);
    return res.status(500).json({
      message: "Failed to return the post",
    });
  }
  if (!doc) {
    return res.status(404).json({
      message: "Post not found",
    });
  }
  res.json(doc);
});
} catch (err) {
console.log(err);
res.status(500).json({
  message: "Error",
  });
 }
};

相关问题