简体   繁体   English

在 findAndCountAll Sequelize 中重命名“行”

[英]Rename “rows” in findAndCountAll Sequelize

Is it possible to have a different key for result.row when using findAndCountAll in Sequelize ?Sequelize中使用findAndCountAll时是否可以为result.row设置不同的键?

I'm using findAndCountAll for pagination .我正在使用findAndCountAll进行分页 I get this structure of data:我得到了这种数据结构:

{
    "count": 8,
    "rows": [
        {
            "id": 6,
            "title": "brands",
            "color": "#D83660",
            "createdAt": "2020-05-12T13:51:47.000Z",
            "updatedAt": "2020-05-12T13:51:47.000Z"
        }
    ]
}

I'd like to rename the "rows" to something else.我想将“行”重命名为其他名称。 How do I do it?我该怎么做? I couldn't find it in the doc.我在文档中找不到它。 https://sequelize.org/master/class/lib/model.js~Model.html#static-method-findAndCountAll https://sequelize.org/master/class/lib/model.js~Model.html#static-method-findAndCountAll

It's not possible with Sequelize.使用 Sequelize 是不可能的。 As you saw in the documentation.正如您在文档中看到的那样。

public static async findAndCountAll(options: object): Promise<{count: number, rows: Model[]}>

This is basically how this function in the library is returning and there are no options to change that.这基本上就是库中这个 function 的返回方式,并且没有任何选项可以改变它。 Thes best you can is to assign result.rows and pack after in.then function or if you use asyc/await after you get it.最好的办法是分配 result.rows 并在 in.then function 或者如果你在得到它之后使用 asyc/await 之后打包。

This is possible in MongoDB but here we don't have a projections.这在 MongoDB 中是可能的,但在这里我们没有预测。

You have two options, fork Sequelize, and change the function so that it returns the new name you want, or if you just want to change the name because you're passing the result somewhere else, as Salesh mentioned, you can do the following:您有两个选择,fork Sequelize,并更改 function 以便它返回您想要的新名称,或者如果您只是想更改名称,因为您将结果传递到其他地方,正如 Salesh 所提到的,您可以执行以下操作:

let result = await MyModel.findAndCountAll()
result.newName = result.rows
delete result.rows

EDIT: alternatively, you might wanna copy them into a whole new object, the returned Sequelize objects usually have extra methods you might not want to invoke accidentally later on, so you'd do编辑:或者,您可能想将它们复制到一个全新的 object 中,返回的 Sequelize 对象通常具有您以后可能不想意外调用的额外方法,所以您会这样做

let data = {
   count: result.count,
   newName: result.rows
}

note: that applies to the objects inside the rows array too.注意:这也适用于 rows 数组中的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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