Insert value in the Mongoose array

Asked

Viewed 686 times

0

My model works as follows. A user has documents, but the user registers before they have these documents. What I’m basically trying to do is to update users in the document array. SCHEMA

'user strict';

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const schema = new Schema({
    email: {
        type: String,
        required: true
    },
    password: {
        type: String,
        required: true
    },
    name: {
        type: String,
        required: true
    },
    documents: [
        {
        title: {
            type: String
        },
        content: {
            type: String
        },
        notes: [
            {
            note: {
            type: String
            }
        }
    ]
    }
]

});

module.exports = mongoose.model('User', schema);

So I looked for some possible answers and I came to this QUERY

exports.put = (req, res, next) => {
    const id = req.params.id;
    User
    .update({id}, {
        $push: {
            "documents.$.title": req.body.title,
            "documents.$.content": req.body.content
        }
    }).then(x => {
        res.status(200).send({
            message: 'Usuário atualizado com sucesso!'
        });
    }).catch(e => {
        res.status(400).send({
            message: 'Falha ao atualizar o Usuário =(', data: e
        });
    });  
};

It returns no error, drops into THEN and gives as if the user had been updated successfully. Could someone help me?

1 answer

1


The correct way to use push is like this:

exports.put = async (req, res, next) => {
    const id = req.params.id;

    const document = {
        title: 'Teste',
        content: 'Teste',
        notes: [
            {note: 'note1'},
            {note: 'note2'}
        ],
        // Por qual motivo notes é um array de objetos e não somente um array?
        // notes: ['note1', 'note2']
    }

    await User.updateOne({ id }, { $push: { documents: document } })
    .then(x => {
        res.status(200).send({
            message: 'Usuário atualizado com sucesso!'
        });
    })
    .catch(e => {
        res.status(400).send({
            message: 'Falha ao atualizar o Usuário =(', data: e
        });
    });  
};

What push does is insert a new Documents object into the Documents array. The easiest and even best way to read is to put the object outside the updateOne.

I also advise you to use some linter. I use JSLINT to keep code clean and uniform. Even working alone, it is interesting in case other programmers help in the future. And even to maintain good programming practices. I use Airbnb’s JSLINT.

  • Thank you so much for the attention and the tips. Thanks to your answer I managed to solve and I am organizing the code better. Over the Notes really was an array, it was not for an array of objects, thank you for noticing.

  • Good, I’m glad you helped. =]

Browser other questions tagged

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