P
P
Pasha1neo2021-05-21 21:59:36
Mongoose
Pasha1neo, 2021-05-21 21:59:36

How to manipulate nested mongoose schemas?

const User = new Schema(name:String, messages:[{message:String}])
async function Create(req, res) {
    const {id} = req.body
    let user = await User.findById(id)
    user.messages.create({message: 'MessageText'})
    user.save()
    res.send(user)
}

The create method does not work, the data is not saved, and there is not even an error.
Are there other ways to manipulate nested schemas? (except push)

Answer the question

In order to leave comments, you need to log in

2 answer(s)
K
Kentavr16, 2021-05-22
@Kentavr16

function is written in a root incorrectly. I recommend reading the mongoose documentation - schema, model. you also need to define a collection in which you will store all this. Among other things, it's not clear to me where you expect to receive this very request - there is no endpoint created that would accept a post request.
The described code should not work. Start by watching tutorials on working with the database.
And yet, asynchronous requests to the server should catch possible errors in a good way - the easiest way is to wrap calls in a try / catch block. Otherwise, you will not understand at what stage something went wrong. You can also watch it on the tube.

A
Alexey Yarkov, 2021-05-22
@yarkov

Am I missing something or should I call user.messages.create?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question