Reputation: 125
I am setting a variable based on a function using findOneAndUpdate() and need everything else to wait until the variable is set. However, when I do this the update runs twice because I use "await" before it.
documentUpdate = { $set: { price: price }, $push: { ips: ipa }, $inc: { likes: 1 }};
returnObject = await getStockWithTrue(stockName, documentUpdate, price);
I later try to return the object and only works if I use await. If i take await away then the function works properly (only updates once) and sends to mongoDB, but then the variable returnObject is not able to be used.
For example, if I use await the return Object will push an ip address twice and increase the likes by 2. Then. If i take await away the returnObject is not the correct model that is returned by getStockWithTrue() because everything is executing before it is complete.
here is the getStockWithTrue function using the findOneAndUpdate()
const getStockWithTrue = (stockName, updateDocument, price) => {
return Stock.findOneAndUpdate(
{ stock: stockName },
updateDocument,
{ new: true, upsert: true },
(error, stock) => {
if (error) return console.log(error);
// If stock is not already in database
if (!error && !stock) {
stock = new Stock({
stock: stockName,
price: price,
likes: 1,
ips: ipa,
});
}
stock.save((error, result) => {
if (error) return console.log(error);
else return result;
});
}
);
};
I'm sure there is a simple solution to solving this, but I have been going at it for days now as the answer is eluding me. Any and all help is appreciated!
Upvotes: 1
Views: 398
Reputation: 1018
I think you are overcomplicating your code. When you are using upsert: true
then you don't need to manually check for the stock and create (if it does not exist). The upsert option will create a document if it does not exist.
The simplified version of your code could be:
documentUpdate = { $set: { price: price }, $push: { ips: ipa }, $inc: { likes: 1 }};
returnObject = await getStockWithTrue(stockName, documentUpdate, price);
Then later
const getStockWithTrue = async (stockName, documentUpdate) => {
return await Stock.findOneAndUpdate(
{ stock: stockName },
documentUpdate,
{
upsert: true,
new: true
}
)
}
Let me know if it helps.
Upvotes: 1