我正在将Web应用程序数据库从Mongoose迁移到Sequelize(以便我可以使用MySQL(。我正在寻找这个猫鼬查询的续集等效物:
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数据类型。
更改实例模型中的数据类型后 -
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
}]
}
}
})