【问题标题】:UnhandledPromiseRejectionWarning: TypeError: Assignment to constant variableUnhandledPromiseRejectionWarning:TypeError:赋值给常量变量
【发布时间】:2020-07-31 09:56:13
【问题描述】:

我在 findAll() 方法之外执行 where 子句,以允许用户在请求正文中发送或不发送过滤器。我的请求正文中的值之一是可以发送或不发送的 categoryId。

这是我的代码:

     const where = {}
        if (categoryId) {
            where = { '$subcategories.category_id$': categoryId
         }
        } 

    try {
            const establishments = await establishment.findAll({
                attributes: [
                    "id",
                    "description",
                    "latitude",
                    "longitude",
                    [sequelize.literal(' (6371 * acos ( '
                        + 'cos( radians(' + latitude + ') ) '
                        + '* cos( radians( latitude ) ) '
                        + '* cos( radians( longitude ) - radians(' + longitude + ') )'
                        + '+ sin( radians(' + latitude + ') )'
                        + '* sin( radians( latitude ))))'), 'distance']
                ],
                include: [{
                    attributes: [],
                    model: subcategory, as: 'subcategories',
                    required: false,
                },
                {
                    attributes: ["id", "name"],
                    model: certificate, as: 'certificates',
                    required: false,
                },
                ],

                where: {
                    where
                },

                establishments: ['id'],
            });
 } catch (error) {
        console.log(error)
        res.status(400).json({ Error: "Error while fetching the establishment" });
    }

给出的错误:

UnhandledPromiseRejectionWarning: TypeError: Assignment to constant variable.
 UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch()

【问题讨论】:

  • 错误其实很明显。您将where 声明为常量,然后尝试为其赋值。
  • 是的,你的权利。
  • 另外我似乎在 $subcategories.category_id$ 上有一个无效的值,我做错了什么吗? @Aioros
  • 我在 $subcategories.category_id$ 上遇到这个错误,说无效值,我做错了什么吗?

标签: javascript node.js sequelize.js


【解决方案1】:

const 变量一旦被声明就不能赋值。

要么使用let

let where = {}

const where = {}
if (categoryId) {
  where['subcategories.category_id'] = categoryId
}

where: { where } 更改为where: where

【讨论】:

  • 它还在 $subcategories.category_id$ 中给我一个无效值,我做错了吗?
  • 尝试删除 $ 符号
  • 试试where : { ...where }
  • 抱歉没听懂,能重复一遍吗? :)
  • 或者你可以做where: where
【解决方案2】:
const where = {}

如果您使用 const 创建变量,则无法再次重新声明它。您应该改用 let

let where = {}

【讨论】:

    猜你喜欢
    • 2020-12-02
    • 2020-06-26
    • 2021-12-04
    • 1970-01-01
    • 2017-08-04
    • 2014-04-30
    • 1970-01-01
    • 2021-12-31
    • 2021-04-07
    相关资源
    最近更新 更多