Create if Findoneupdate does not find anything

Asked

Viewed 25 times

-2

Hello, I am developing an application in Node.js and I am having difficulty.

In case my findOneUpdate doesn’t find anything I wanted a create to be done, but I couldn’t find a way to create an if or something.

follows the code:

Exports.getAndUpdateByNome = async (date) => { await staticAnalise . findOneAndUpdate(date.name, { $set: { name: date.name, date: date.date } }); }

  • Welcome to Sopt. With so little information it is impossible to suggest anything. Try to be clearer in your question and add more information, such as the database that is used.

1 answer

0

Information is missing in this question, what this refers to findOneAndUpdate?

From the code we can deduce that it is a Mongodb method, but the tags or the question say nothing about.

In any case, the method findOneAndUpdate receives three parameters: filters to find the document that will be modified, updates, and options. One of these options is the upsert, that when activated, creates a new document using these updates if no document has been found with your filters.

Example:

staticAnalise.findOneAndUpdate(
    { nome: data.nome }, 
    { $set: {
        nome: data.nome,
        data: data.data
    } },
    { upsert: true }
)
  • I thank you for your reply, I have tried here and recorded over the data already present, changing the information completely.

  • but did not create a new document.

  • @TFGROOVE, but isn’t that what you asked for? If you find a document, update, if you don’t, create a new one. Or the goal was to return an error if there was already a document with the same name as the database?

  • So he didn’t create a new one He altered my present tense there

Browser other questions tagged

You are not signed in. Login or sign up in order to post.