Yu Hien Ng
Yu Hien Ng

Reputation: 45

Mongoose Error when using findOneAndUpdate

I have received an error at my server console during updating my Note collection, the update is successful but I receive this error in my server console, felt something wrong. Thanks in advance

app.put("/todos/:id", async(req,res) => {
    try {
        // console.log(req.body);
        const { id } = req.params;
        const { title, content } = req.body.edit;
        const edit = await Note.findOneAndUpdate({_id:id}, {
                title: title,
                content: content
            },
            function (err, docs) {
            if(!err){
                console.log("Successfully edit item:" + docs);
                const response = res.json(docs);
            }else{
                console.error(err);
            }
        })
        // Example: Update name to Gourav
        // User.findByIdAndUpdate(user_id, {
        //         name: 'Gourav'
        //     },
        //     function (err, docs) {
        //         if (err) {
        //             console.log(err)
        //         } else {
        //             console.log("Updated User : ", docs);
        //         }
        //     });
    } catch (error) {
        console.error(error);
    }
});

Error msg:

MongooseError: Query was already executed: Note.findOneAndUpdate({ _id: new ObjectId("61580e469338c1fc3... at model.Query._wrappedThunk [as _findOneAndUpdate] (C:\Users\xx\Desktop\MernToDoV3\server\node_modules\mongoose\lib\helpers\query\wrapThunk.js:21:19) at C:\Users\xx\Desktop\MernToDoV3\server\node_modules\kareem\index.js:370:33 at processTicksAndRejections (internal/process/task_queues.js:77:11) { originalStack: 'Error\n' + ' at model.Query._wrappedThunk [as _findOneAndUpdate] (C:\Users\xx\Desktop\MernToDoV3\server\node_modules\mongoose\lib\helpers\query\wrapThunk.js:25:28)\n' + ' at C:\Users\xx\Desktop\MernToDoV3\server\node_modules\kareem\index.js:370:33\n' + ' at processTicksAndRejections (internal/process/task_queues.js:77:11)' }

Upvotes: 1

Views: 1389

Answers (2)

Yilmaz
Yilmaz

Reputation: 49301

I had similar issue with this query query.limit(resPerPage).skip(skip).

I chained clone() and it worked

query.limit(resPerPage).skip(skip).clone()

Upvotes: 1

Apoorva Chikara
Apoorva Chikara

Reputation: 8773

You can do something like this. You don't need to use the callbacks instead use async/await or then/catch.

When you apply try/catch to the async code, it doesn't go well. They are typically used to catch the errors when the code is synchronous by using different means. Promises provided a way to catch the error using catch operator.

app.post("/todos", async (req,res)=>{
    try{
        // const small = new Tank({ size: 'small' });
        // small.save(function (err) {
        // if (err) return handleError(err);
        // // saved!
        // });

        console.log(req.body); //should use console to see

        const { title, content}  = req.body.newNote,
              noteInput = new Note({title, content });
     
        const result = await noteInput.save();
        
        if (result) {
         // check if the result exist else do something 
         // if you don't find anything
        }

    }catch(err){
        // any errors in the save will be catch here automatically
        console.error(err.message);
    }
});

Note: When you make a function async, you need to use the await keyword to wait for the results for the async portion in the function.

Upvotes: 0

Related Questions