Home > front end >  Mongoose: How to push new value into specific key?
Mongoose: How to push new value into specific key?

Time:11-19

I have this function that will update my task collection. The problem is how can I add new value into the array of a specific attachment using $push.

Schema

const taskSchema = mongoose.Schema({
  projectId: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'projectModel',
  },
  attachments: [
    {
      fileThumbnail: { type: String },
      name: { type: String },
      size: { type: Number },
      uploadDate: { type: String },
      status: {
        type: Boolean,
        default: true,
      },
    },
  ],
});

taskController

export const updateTaskById = async (req, res) => {
  try {
    const {
      _id,
      projectId,
      attachments,
    } = req.body;

    const task = await taskModel.findById(req.params.id);
    if (task) {
      task.invitedPeopleId = invitedPeopleId || task.invitedPeopleId;
    }

await task.save({
      validateBeforeSave: false,
    });

  } catch (error) {
    console.log(error.message);
  }
};

Solution I tried

taskModel.updateOne(
  { projectId: projectId },
  { $push: { attachments: attachments } },
);

CodePudding user response:

You may be conflating Models and Schemas, a common misunderstanding.

You created a Schema but did not compile a Model from that Schema. This is how you might compile the Model.

const Task = mongoose.model('task', TaskSchema, 'tasks')
export default Task

Then, in your taskController, import the Model to manipulate documents.

import Task from '../models/task.model.js'

Finally, use the updateOne method to modify the document:

Task.updateOne(
      {
        projectId: 1,
      },
      {
        $push: {
          attachments: {
            name: 'file4',
            size: 4,
          },
        },
      }
    )

This Mongo playground demonstrates the update.

  • Related