Search code examples
node.jsmongoose

Cannot add property to object in NodeJS


I'm trying to write a function to response http request. This is my code:

const listTask = async (req, res) => {
    let tasks = await Task.find();
    let works = await Work.find().select({_id: 1, name: 1});
    tasks.forEach(t => {
      work = works.find(c => parseInt(c._id) === parseInt(t.work_id));
      t.work = work;
      console.log(t);
    });
    res.status(200).json(tasks);
}

In this function, Task and Work are models created by mongoose. A loop by forEach to search each elements in array tasks. Here, i want to create new property to store work object. But message in console doesn't have work property.

I tried to use console.log(t.work), the message is same with work. I also wrote a similar function:

function get_full_name_display(users){
    users.forEach(u => {
        u.full_name_display = u.full_name;
    })
    return users;
};

and this function worked perfectly. So anyone can explain why and suggest a solution?

Thanks so much. Sorry for bad English, i've used Translate Tools a lots.


Solution

  • first thing as mentioned above also is your 'work' variable is not declared properly. Another point is that any result returned from mongoose model is immutable(i.e mongoose objects and not plain js objects), so you cannot directly change properties in 'tasks'. try the below code:

    const listTask = async (req, res) => {
        let tasks = await Task.find().lean();
        let works = await Work.find().select({_id: 1, name: 1}).lean();
        tasks.forEach(t => {
          const work = works.find(c => parseInt(c._id) === parseInt(t.work_id));
          t.work = work;
          console.log(t);
        });
        res.status(200).json(tasks);
    }
    

    you can read more about lean on here: https://mongoosejs.com/docs/tutorials/lean.html