简体   繁体   中英

sequelize update column by id from object array

I have a table:

id, url, storage
3, www.a.com, null
7, www.b.com, null

Now I fetch the html and save it in a location (storage).

My code produces an object with the ids and their corresponding storage locations:

{ 
    3: 'C:',
    7: 'D:'
}

How can I batch update the entries from this information so it will become

id, url, storage
3, www.a.com, C:
7, www.b.com, D:

I use sequelize to communicate with the DB

Model is an instance of your model, that connects to you table. It would have 3 attributes: id, url, storage .

For example, this is how I assume you have set it up:

var Model = db.define('Model',
  {
    id: { type: Sequelize.INTEGER },
    url: { type: Sequelize.TEXT },
    storage: { type: Sequelize.STRING(1) }
  },
  {
    tableName: 'my_table_name',
    timestamps: false
  });

Now you can use the findAll() method to retrieve all entries in your table, filter them based on your object, and set the storage property on the entries and save to DB:

var obj = {3: 'C:',7: 'D:'};

Model.findAll()
  .filter(function(entry) {
    // filter returns only those entries that have IDs present in the obj
    return obj.hasOwnProperty(entry.id);
  })
  .map(function (filteredEntry) {
    // Ex.:
    // filteredEntry = {"id": 3, "url": "www.a.com", "storage": null}
    // obj[filteredEntry.id] == obj[3] == 'C'
    filteredEntry.storage = obj[filteredEntry.id];
    return filteredEntry.save();
  })
  .then(function (entries) {
    //Do something else
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM