我正在将 Web 应用程序数据库从 Mongoose 迁移到 Sequelize (这样我就可以使用MySQL)。我正在寻找与此 Mongoose 查询等效的 Sequelize:
models.Instance.find({ "events.id": eventID })
该查询使我能够找到包含 id == eventID 的事件(在事件数组内)的实例。
我尝试了以下方法,但没有给出所需的结果:
models.Instance.findAll({
raw: true,
where: {
"events.id": eventID
}
})
Sequelize 中的实例模型如下所示:
module.exports = function(sequelize, DataTypes) {
var Instance = sequelize.define('Instance', {
name: {
type: DataTypes.STRING,
},
description: {
type: DataTypes.STRING,
},
events: {
type: DataTypes.JSON,
}
});
return Instance;
};
最佳答案
我找到了一个解决方案,其中涉及切换到 PostgreSQL 数据库,因为它支持 JSONB data type .
更改实例模型中的数据类型后 -
events: {
type: DataTypes.JSONB,
}
我使用此代码进行查询:
var models = require('../../models');
const Op = models.Sequelize.Op;
models.Instance.findAll({
raw: true,
where: {
events_current: {[Op.contains]:[{
id: eventID
}]
}
}
})
关于javascript - 如何通过查询字典数组中的键/值来查找 Sequelize 中的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55829157/