Reorganize Sequelize results

时间:2016-04-12 00:30:27

标签: javascript node.js sequelize.js

I'm doing a complex findAll in Sequelize with lots of includes, like this.

const versions = yield Version.findAndCountAll({
  order: [['createdAt', 'DESC']],
  attributes: ['description', 'createdAt', 'id'],
  include: [{
    model: Section,
    attributes: ['slug'],
    where: { slug: section },
    include: [{
      model: Type,
      attributes: ['slug'],
      where: { slug: type },
      include: [{
        model: Group,
        attributes: ['slug'],
        where: { slug: group }
      }]
    }]
  }]
});

The results then come out like this:

{
  "description": "Wow. Nice one.",
  "createdAt": "2016-04-11T23:05:15.736Z",
  "body": "hi",
  "id": 10,
  "Section": {
    "slug": "ttyl",
    "Type": {
      "slug": "Test",
      "Group": {
        "slug": "python2",
      }
    }
  }
}

The depth that their nested to makes the result a little unpleasant to work with. I'd like it more like this, if possible

{
  "description": "Wow. Nice one.",
  "createdAt": "2016-04-11T23:05:15.736Z",
  "body": "hi",
  "id": 10,
  "Section": "ttyl",
  "Type": "Test",
  "Group": "python2"
}

Is this possible?

1 个答案:

答案 0 :(得分:1)

您可以通过设置raw:true来展平某些范围。 Raw true将变为flat.subproperty.property等等。包含'as'选项允许您对这些属性进行别名。但我不相信你可以自动完全重塑对象(至少我没有在文档中找到任何东西)。从上面的例子中,我相信,你最终必须添加自己的映射步骤。

public class JavaUpdateArrayElement {
    public static void main(String args[]) throws UnknownHostException {

        MongoClient mongo = new MongoClient();
        DB db = mongo.getDB("databaseName");

        DBCollection coll = db.getCollection("test");

        /*
            MONGO SHELL : 
            db.test.update(
                { "detailist.code": "456"},
                {
                    "$set": { "detailist.$.School": "foo" }
                }
            )
        */

        // build the query { "detailist.code": "456"}
        BasicDBObject query = new BasicDBObject("detailist.code", "456");

        // build the update document
        BasicDBObject data = new BasicDBObject();
        data.put("detailist.$.School", "foo");

        BasicDBObject update = new BasicDBObject();
        update.put("$set", data);

        // run the update operation
        coll.update(query, update);     

    }
}