1

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)' }

2 Answers 2

1

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

I chained clone() and it worked

query.limit(resPerPage).skip(skip).clone()
Sign up to request clarification or add additional context in comments.

2 Comments

Indeed it helps! Could you enlighten me how it resolve the error? Previously keep emits error despite all data is successfully edited. Is it because when I accidentally run the queries for multiple times causing previous errors?
I think it was becuase mongoose is not allowed to make same queries twice. so somehow mongoose is making 2 queries in a row. with clone it is creating a different copy each time.
0

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.

3 Comments

Sorry, i found that i had attached wrong code snip due to yesterday stackoverflow server issue, never notice until i come back from work, thanks for your reply anyway
So, Does it work?
No it does not.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.