0

I have the following project document with the developers field. I want to push multiple records returned from a mySQL query.

/* project document */
{
    "_id" : ObjectId("5ad77d2ccec38c21b8cbea0b"),
    "description" : "blah blah blah",    
    "startDate" : null,
    "completedOn" : null,
    "lastStatusOn" : null,
    "status" : "Unassigned",
    "devTime" : "00:00:00.0000000",
    "devLevel" : "Basic",
    "estDevTime" : "00:00:00.0000000",
    "developers" : [],
    "notes" : [],
    "__v" : 3
}

I get the following data return from mySQL.

[ RowDataPacket { userid: 'jd1234', fullName: 'Joh Doe' },
  RowDataPacket { userid: 'jd5678', fullName: 'Jane Doe' } ]

I want to push this data into the developers array in the project document.

Desired result:

/* project document */
{
    "_id" : ObjectId("5ad77d2ccec38c21b8cbea0b"),
    "name" : "shopping cart",
    "description" : "blah blah blah",    
    "startDate" : null,
    "completedOn" : null,
    "lastStatusOn" : null,
    "status" : "Unassigned",
    "devTime" : "00:00:00.0000000",
    "devLevel" : "High",
    "estDevTime" : "00:00:00.0000000",
    "developers" : [
        { userid: 'jd1234', fullName: 'Joh Doe' },
        { userid: 'jd5678', fullName: 'Jane Doe' }
    ],
    "notes" : [],
    "__v" : 3
}

I have the following code. I get no error but the developers does not get inserted.

router.post('/saveDeveloper', async (req, res) => {
  let userList = req.body.attuid,
      users = userList.split(',').map(attuid => `'${attuid.trim()}'`).join(',');


  mySQLdb.connect();
  let sql = `SELECT userid, fullName FROM users WHERE userid IN (${users})`;

  mySQLdb.query(sql, function (err, results) {
    if (err) throw err;
    console.log(results);

    Project.update(
      {_id: req.body.projectID},
      {"$push": {
        "developers": {"$each": results}
        }
      }
    );

    res.json(results);    
  });

  mySQLdb.end();

});

What am I missing?

halfer
  • 19,824
  • 17
  • 99
  • 186
user752746
  • 617
  • 9
  • 31

1 Answers1

0

This is because you are returning the results of the first query, the sql one. results is an array returned by sql query and you are sending that data in response.

If you want to send the updated results you'll have to send in the response of the results obtained after updating the collection and you;ll get the updated results in the callback function of .update(.. Something like this

Moreover, you;ll have to work on data results to convert it into json, so you can add these steps to manipulate results

var string=JSON.stringify(results);
var json =  JSON.parse(string);
Project.update(
  {_id: req.body.projectID},
  {"$push": {
    "developers": {"$each": json }
    }
  },function(err,resp){

    res.json(resp)
  }
);
Muhammad Usman
  • 10,039
  • 22
  • 39