Need help updating Mongoose object data

Hi All,

I have a Mongoose Schema and Model shown below:

const DataSchema = new Schema(
    name:{type: String, default: ""},
    task: {type: Schema.Types.Mixed, default: {}}
  { timestamps: true, _id: true, minimize: false, strict: false }

const Data = mongoose.model("Data", DataSchema);

Now when a user profile is created using the “name” parameter I would get the following response as an example:

{"success: true, "data":[{"name":"Eminem","_id":"5ee8468316a2ea32bcfbf411","task":{},"createdAt":"2020-06-16T04:11:47.441Z","updatedAt":"2020-06-16T04:11:47.441Z","__v":0}]}

My next action is to update the task object based on user’s input for the “taskName”. For example: if a user inputs “work” as “taskName”, I want the task object to be updated as "task": {work:{}}.

For that I used the method below but it never updates the “task” object. Can anyone see what I am doing wrong?

var id = "5ee8468316a2ea32bcfbf411"
var taskName="work"
var key = 'task.'+taskName
var push = {}

Data.findByIdAndUpdate({_id:id}, push, (err,data)=> {
      if(err) throw err

I appreciate the help.

You need to tell what you want to update, and show success if you wish.

Data.findByIdAndUpdate({_id:id}, {name: 'lol'}, (err,data)=> {
      if(err) throw err
      return data


Thanks for the response. But I think that is what I tried to do by putting “push” in the findByIdAndUpdate function. As I defined it push = { {}}. Is that not the right way to update the object “task” using a variable object key?

Hello there,

I am not all to experienced with Mongoose, but you are not returning your altered document. Generally, this is done using the aptly-named done() callback, but you can just ensure you are returning the data once updated…

Hope this helps


Thanks for point that out. But I have a different getData route I am using that specifically retrieves the updated data and I know the route works because when I update other parameters in the data I see the change.

I am pretty sure the problem has to do with the Mongoose function to update the data but I can’t find a documentation that shows how to update objects when you are using a variable key.

For anyone wondering what the solution is I was able to get the answer on stackoverflow. Thanks to,

Solution is:

let id = "5ee8468316a2ea32bcfbf411"
let taskName="work"
      (err,data)=> {
      if(err) throw err