Home > Blockchain >  Trying to populate with $push mongoose, but the result is null
Trying to populate with $push mongoose, but the result is null

Time:05-07

i'm trying to populate using mongoose and $push but got null, and using postman it's says that the req.body is undefined. Can't see why(i'v added app.use(express.urlencoded({ extended: true }))) as a middleware. I want to send a message to the given user basically, but can't see what i'm doing wrong.

Here are the models:

User:

const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    messages: [
        
    ]
});

Message:

const messageSchema = new mongoose.Schema({
    message: {
        type: String,
        required: true
    }
});

Here's the express route:

router.post('/send-message/:id', (req, res) => {
    return Message.create({ message: req.body.message })
        .then((result) => {
            return User.findByIdAndUpdate(req.params.authorId, {
                $push: { messages: result }
            }, {
                new: true
            }).exec((err, result) => {
                if (err) {
                    res.send('error')
                } else {
                    res.send({ result })
                }
            })
        });
});

And here's a simple form:

<div>
    <form method="POST">
        <textarea  name="message"></textarea>
        <input type="submit">
    </form>
</div>

CodePudding user response:

  • Do this to your schema
const userSchema = new mongoose.Schema({
    name: {
        type: String,
        required: true
    },
    ...
    messages: { 
        type: Array, 
        of: messageSchema
    },
});
  • The form must have an action. Something like action="/send-message/<id>"
  • The params don't match in your code. If this is a typo, ignore this, or else the :id in /send-message/:id can be accessed like this req.params.id and not req.body.authorId

CodePudding user response:

I'm using handlebars, so it's working even without action="/". The problem was here :

<div >
    <a href="/send-message/{{authorId}}">Contact seller</a>
</div> 

I specify it as that, so it wasn't working.

  • Related