Reputation: 1048
I am very confused to use Bookshelf model to insert data to database in this situation:
I am using these libs: knex, bookshelf, express, body-parser, and mysql database
I have a table on db is called location, it contains below column:
loc_id
, latitude
, longitude
, time
This location is sending from one user, so I need to save loc_id
in another table with user_id
to save a location (single object) without saving user_id I use this code:
.post(function (req, res) {
Loc.forge({latitude: req.body.location.lat,
longitude: req.body.location.lng,
date:req.body.time,
speed:req.body.speed,
gpsAnten:req.body.gpsAnten})
.save()
.then(function (location) {
res.json({error: false, data: {id: location.get('id')}});
})
.catch(function (err) {
res.status(500).json({error: true, data: {message: err.message}});
});
});
but now, I am sending post request by body like below from my device:(it is JSON format)
{
"user_id": 135,
"locations": [
{
"id": 1,
"latitude": "35.374760",
"longitude": "51.5123916",
"date": "0000-00-00 00:00:00"
},
{
"id": 2,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
},
{
"id": 3,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
},
{
"id": 4,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
},
{
"id": 5,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
},
{
"id": 6,
"latitude": "35.6247466",
"longitude": "51.51241",
"date": "0000-00-00 00:00:00"
}
]
}
How could I save each location in location
table and get this Id, then save its loc_id
and user_id
in loc_user
table ?
Upvotes: 0
Views: 963
Reputation: 1048
At least I found the solution to fix this issue; here is my code:
.post(function (req, res) {
deviceId = req.body.id
locationArray = req.body.frame;
locationArray.forEach(function(element) {
console.log(element);
Loc.forge({latitude: element.location.lat,
longitude: element.location.lng,
date: element.time,
speed: element.speed,
gpsAnten: element.gpsAnten})
.save()
.then(function (location) {
userDevice.forge({
device_id: deviceId,
location_id: location.get('id')
})
.save()
.then(function(middleware) {
console.log('Save middleware');
})
.catch(function(err) {
console.log('Error middleware:' + err.message);
})
})
.catch(function (err) {
console.log('Error location:' + err.message);
});
});
});
It is not as clear as I need but seems is only solution.
Upvotes: 1