javascript - 使用 sequelize 中的 where 条件根据距离进行过滤

标签 javascript node.js sequelize.js

我必须根据与当前位置的距离过滤帖子。附上了下面的代码以供引用,但它不起作用(尽管计算距离工作正常),只有在距离条件似乎不起作用的情况下。此外,当我在条件的顶部尝试距离过滤器时,它会抛出我posts.distance column not found 错误

const posts = await Post.findAll({
        where: {
            mobile: {
                [Op.ne]: mobile,
            },
        },
        attributes: 
            include: [
                [
                    db.Sequelize.fn(
                        "ST_Distance",
                        db.Sequelize.col("location"),
                        db.Sequelize.fn(
                            "ST_MakePoint",
                            parsedLocation.lat,
                            parsedLocation.lng
                        )
                    ),
                    "distance",
                ],
            ],
            where: {
                distance: {
                    [Op.between]: [
                     0,100
                    ],
                },
            },
        },
        include: {
            model: UserProfile,
            attributes: ["username"],
        },
    });

最佳答案

也许如果您将 where 距离条件移出第一个移动设备 where 内的包含条件。
此外,我建议将您的属性移到第一个 where 条件之上。
希望这些更改将修复您的错误或使您走向解决方案。

const posts = await Post.findAll({
    attributes: 
        [[
            db.Sequelize.fn(
                "ST_Distance",
                db.Sequelize.col("location"),
                db.Sequelize.fn(
                    "ST_MakePoint",
                    parsedLocation.lat,
                    parsedLocation.lng
                )
            ),
            "distance"
        ]],
    where: {
       [Op.and]: {
            mobile: {
                [Op.ne]: mobile,
            },
            distance: {
                [Op.between]: [
                 0,100
                ],
            }}
    },
    include: {
        model: UserProfile,
        attributes: ["username"],
    },
});

关于javascript - 使用 sequelize 中的 where 条件根据距离进行过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66125499/

相关文章:

postgresql - 序列化 JOSNB 查询

node.js - 错误 : XModel is not associated to Ymodel on Sequelizejs

javascript - Trentrichardson 日期时间选择器不起作用

javascript - 尝试将 "var app"传递给函数

linux - Node.js 集群 - 检测工作线程卡住了吗?

javascript - 如何在对象字符串中插入单个反斜杠?

node.js - 如何将时区设置为 "-03:00", Sequelize cli

javascript - 路口观察者 polyfill 不工作 Safari

javascript - 在库外调用库的函数

javascript - 为什么这两种进行异步调用的方法(一种使用 Promise,另一种使用生成器)不会产生相同的结果?