Problems with Mongoosis function (nodejs)

Asked

Viewed 43 times

-2

Hello, I’m having problems with a learning mini-api that I’m doing, I’m not an advanced user, but I’ve been dealing with Nodejs for a long time, I decided to create a mini-api without looking at tutorial, only Docs, but I came across this error, and I couldn’t understand, I think it’s easy, so to save time I decided to come here ask.

The error that I’d like to at least understand is this, which refers to index.js in the Product.create line that I didn’t understand why it went wrong, and to look at the rest of the code,: https://github.com/Raisler/expressApi-example inserir a descrição da imagem aqui

1 answer

1


By mistake Product.create is not a function it seems clear to me that the error is in the module ProdutoM, not in the index.

In ProdutoM you are exporting your module in the following way:

module.exports = ("Produto", ProdutoSchema)

I imagine your intuition would be as follows:

module.exports = mongoose.model("Produto", ProdutoSchema)

Now, even if you are exporting the module correctly, your code will still not work, as you are not establishing a database connection. Remember to import the .src/db/database.js in his index. Only the action of importing the module is enough, because you only need the code in this module to be executed when starting the server.

And finally, remember to send a reply to the user after the Produto.create(). No need to use produto.save() in that case, the create already saved in the database, save would only be necessary if you had created or changed an instance of mongoose.model and it needs to be updated in the database:

app.post('/registro', async (req, res) => {
    try {
        await Produto.create(req.body);
        res.send('ok');
    } catch {
        res.status(500).send('erro');
    }
})

Browser other questions tagged

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