Creating New Child Added To The Array Field

Viewed 43

I'm not sure this was the right query to create a object because once I use my Postman it returns undefined.

Here's my schema.

import mongoose from 'mongoose';

    const todoSchema = mongoose.Schema({
        username: {
            type: String,
        },
        password: {
            type: String,
        },
        task: [{
            id: mongoose.Types.ObjectId,
            post: String,
        }],
        time: {
            type: Date,
            default: Date.now,
        }
    });
    
    const TodoModels = mongoose.model('TodoModels', todoSchema);
    
    export default TodoModels;

Here's my Postman. I'm using patch because I was trying to add object on existing user.

    {
        "task": [
                {
                "post": "task"
            }
        ]
    }

Here's my approach for adding new object array field.

    export const addTask = async (req,res) => {
        const { id } = req.params;
 
        if(!mongoose.Types.ObjectId.isValid(id)) return res.status(404).json(`Invalid ID`);
    
        const updatedPost = await TodoModels.findByIdAndUpdate(id,{$push:{task:                                                                 
        {post: req.body.task.post }}},{ new: true });
    
        res.json(updatedPost);
    }

Unfortunately the req.body.task.post returns undefined.

1 Answers

req.body.task is an array. So you have to access the post with req.body.task[0].post.

const updatedPost = await TodoModels.findByIdAndUpdate(id,{$push:{task:{post: req.body.task[0].post }}},{ new: true });
Related