简体   繁体   English

mongoose findOneAndUpdate 完成更新后如何运行回调?

[英]How to run callback after mongoose findOneAndUpdate finish updating?

In my API i have the express's app.put method,where i search in a collection for a document with a specific title with mongoose's findOneAndUpdate method and update it.在我的 API 中,我有 express 的app.put方法,我使用 mongoose 的findOneAndUpdate方法在集合中搜索具有特定标题的文档并更新它。


    app.put("/articles/:articleTitle",(req, res) => {

        Article.findOneAndUpdate({
               title: req.params.articleTitle
           }, {
               title: req.body.title,
               content: req.body.content
           }, (err, foundArticle) => {
               err ? res.send("Error !") : foundArticle ? res.send("Article found.Updating...") : res.send("NO articles found to update!")
           })

       })

How can i run a callback function AFTER the update has finished,and maybe return the updated document?如何在更新完成后运行回调 function,并返回更新后的文档? I have tried to add a .then at the end of findOneAndUpdate method but it throws me this error: "MongooseError: Query was already executed: Article.findOneAndUpdate..."我试图在findOneAndUpdate方法的末尾添加一个.then但它抛出了这个错误: “MongooseError:查询已执行:Article.findOneAndUpdate ...”

I have also tried to pass the method's return value in a variable and access it in .then but it throws the same error like so:我还尝试在变量中传递方法的返回值并在.then中访问它,但它会引发相同的错误,如下所示:


    app.put("/articles/:articleTitle",(req, res) => {
        
       const doc = Article.findOneAndUpdate({
               title: req.params.articleTitle
           }, {
               title: req.body.title,
               content: req.body.content
           },{returnDocument: 'after'}, (err, foundArticle) => {
               err ? res.send("Error !") : foundArticle ? res.send("Article found.Updating...") : res.send("NO articles found to update!")
           }).then( () =>{ console.log(doc) })
           
       })

EDIT: It seems that when i simply add the option returnDocument: 'after' as a parameter,it gives me access to the "after" document inside its own method callback,hmm,i have to check the docs but if anyone knows the common practice to do this i would appreciate it !编辑:似乎当我简单地添加选项returnDocument: 'after'作为参数时,它让我可以访问它自己的方法回调中的“after”文档,嗯,我必须检查文档,但如果有人知道共同点练习这样做,我将不胜感激!


        Article.findOneAndUpdate({
            title: req.params.articleTitle
        }, {
            title: req.body.title,
            content: req.body.content
        },{returnDocument: 'after'}, (err, foundArticle) => {
            err ? res.send("Error !") : foundArticle ? res.send(foundArticle) : res.send("NO articles found to update!")
        })

According to the docs , findOneAndUpdate() :根据文档findOneAndUpdate()

[...] finds the first document that matches a given filter, applies an update, and returns the document. [...] 找到与给定过滤器匹配的第一个文档,应用更新并返回该文档。 By default, findOneAndUpdate() returns the document as it was before update was applied.默认情况下,findOneAndUpdate()返回应用更新之前的文档。

To actually return the updated document, the documentation suggests to do the following:要实际返回更新的文档,文档建议执行以下操作:

You should set the new option to true to return the document after update was applied.您应该将新选项设置为 true 以在应用更新后返回文档。

The third argument to the method is an optional options object where a new parameter can be set to true in order to actually return the updated document.该方法的第三个参数是一个可选options object ,其中可以将new参数设置为true以实际返回更新的文档。

To actually access the updated document after the method call, there are multiple ways of doing so.要在方法调用后实际访问更新的文档,有多种方法可以这样做。

Example 1: Using async/await syntax示例 1:使用 async/await 语法

const doc = await Article.findOneAndUpdate(
    { title: req.params.articleTitle },
    {
        title: req.body.title,
        content: req.body.content
    },
    { new: true }
)

doc.title // equals value of req.body.title

Example 2: Using .then() syntax示例 2:使用.then()语法

Article.findOneAndUpdate(
    { title: req.params.articleTitle },
    {
        title: req.body.title,
        content: req.body.content
    },
    { new: true }
).then((err, doc) => {
    console.log(doc.title) // equals value of req.body.title
})

Example 3: Using the callback syntax示例 3:使用回调语法

Article.findOneAndUpdate(
    { title: req.params.articleTitle },
    {
        title: req.body.title,
        content: req.body.content
    },
    { new: true },
    (err, doc) => {
        console.log(doc.title) // equals value of req.body.title
    })

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM