Chris Gregorio
Chris Gregorio

Reputation: 169

Node - Workaround for Mongoose pushing twice after saving twice

I would like to know the proper way to solve this problem. I am referencing a collection via mongoose in my node code. I have certain functions which modify the document and after each section of edits I want to save it (Due to the fact the code is unsure if it will need to be saved again somewhere else in the code). I could write some pretty convoluted code to determine which save should be the last save which I have been doing, but it's causing the code to become extremely complex for what seems like no good reason.

Basically my code ends up looking like this:

collection.attributeArray.push(item);
collection.save();
collection.save();

This results in attributeArray looks like this

[item, item]

instead of simply

[item]

Is there a reasonable way to accomplish this without knowing which save will be your final one?

Upvotes: 0

Views: 1044

Answers (2)

user1784176
user1784176

Reputation:

Mongoose tracks push changes on document arrays by registering an atomic $pushAll operation. A workaround for this would be to do

collection.attributeArray = collection.attributeArray.concat([ item ]);

Upvotes: 1

Semih Gokceoglu
Semih Gokceoglu

Reputation: 1428

It is really hard to see the problem without all code block. Please add your whole code block.

But, I have a guess. Probably, your collection.attributeArray.push(item);in a loop. Pushing item twice and it saves multiple times. As I mentioned, It is just guess. Otherwise, double saving do not affect to add items twice.

In another issue, why do you use .save() 2 times? just use one time before calling your callback(or end of your code).

Upvotes: 0

Related Questions