Bookshelf,Knex和mysql保存对象列表

时间:2017-01-15 18:32:59

标签: mysql node.js express knex.js bookshelf.js

在这种情况下,使用Bookshelf模型将数据插入数据库非常困惑:

我正在使用这些库: knex,书架,快递,正文解析器和mysql数据库

我有一个关于db的表叫做location,它包含以下列: loc_idlatitudelongitudetime

此位置是从一位用户发送的,因此我需要将loc_id保存在另一个包含user_id

的表格中

保存位置(单个对象)而不保存user_id我使用此代码:

.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}});
    });
  });

但是现在,我正在通过我的设备发送下面的正文请求:(它是JSON格式)

{
  "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"
      }
  ]
}

如何在location表中保存每个位置并获取此ID,然后将其loc_iduser_id保存在loc_user表中?

1 个答案:

答案 0 :(得分:1)

至少我找到了解决这个问题的解决方案;这是我的代码:

  .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);
});
   });
  });

它并不像我需要的那样清晰,但似乎只是解决方案。