I'm currently using SailsJS framework, and i'm trying to update an array of elements using only one query in my MongoDB database.
Here is what I'm doing but records are not updated..
Incoming JSON:
{
"cars": [
{
"id": "5cb5cbd5c395a01b4c9d86da",
"latitude": "-5",
"longitude": "551"
},
{
"id": "5cb5cbd7c395a01b4c9d86db",
"latitude": "-4",
"longitude": "4421",
}
]
}
Controller:
async setLocationOfCars(req, res) {
try {
sails.log.info(controllerName + "::" + req.options.action + "() - called");
const carsLocationArray = req.body.cars;
let response = CarService.setLocationOfCars(carsLocationArray);
switch (response.status) {
case constants.RESOURCE_SUCCESSFULLY_UPDATED :
return HttpResponseService.json(200, res, constants.RESOURCE_SUCCESSFULLY_UPDATED, response.data);
default:
return HttpResponseService.internalServerError(res, response);
}
} catch(err) {
return HttpResponseService.internalServerError(res, err);
}
}
Service:
async setLocationOfCars(cars) {
try {
const arrayOfIdsUpdated = [];
_.forEach(cars, async function(car){
let attributesToUpdate = {};
if (car.hasOwnProperty("latitude")) {
attributesToUpdate.latitude = car.latitude;
}
if (car.hasOwnProperty("longitude")) {
attributesToUpdate.longitude = car.longitude;
}
await Car.updateOne({
id: car.id
}).set(attributesToUpdate);
arrayOfIdsUpdated.push(gateway.id)
});
return {
status: constants.RESOURCE_SUCCESSFULLY_UPDATED,
data : arrayOfIdsUpdated
};
} catch (err) {
return {
status : constants.DATABASE_ERROR,
name : err.name ? err.name : "",
message: err.message ? err.message: "",
stack : err.stack ? err.stack : "",
code : err.code ? err.code : "",
};
}
}