Search code examples
mongoosedocumentupdating

Mongoose Updating document without even running save() function


I am using express. I have file paths in MongoDb, before sending response from Api. I am prepending the api Url with the file path like

song.path = url + song.path;
res.send(song);

but what this is doing that it updates the path in mongodb as well, even though i am not saving this doc, i amd just sending the response

i have tried

const newSong = song;
newSong.path = url + newSong.path;
res.send(newSong)

;

but this didnt help, document is still updating.

This is my controller

    const song = await Song.findOne({ 'lastPlayed': false }).sort("-totalRating");
    song.lastPlayed = true;
    song.save();
    song.path = url + song.path;
    res.send(song);

it should only update the property for response.. not in Db

UPDATE

If i comment out song.save() path doesnt get updated.


Solution

  • What is happening is that doc.save() is asynchronous, when you mutate the object and send the response doc.save() only execute after the main thread that is why song.path = url + song.path; gets copy to mongoDB even though you think you save it before.

    you can create a new object just for the response

    const song = await Song.findOne({ 'lastPlayed': false }).sort("-totalRating");
    song.lastPlayed = true;
    song.save();
    res.send({ ...song, path: url + song.path });
    

    Or you can await the save and then mutate the object for your response, this is good if you want to handle errors before sending the response.

    const song = await Song.findOne({ 'lastPlayed': false }).sort("-totalRating");
    song.lastPlayed = true;
    await song.save();
    song.path = url + song.path;
    res.send(song);