gpt4 book ai didi

rxjs - 将 sequelize Promise 转换为可观察的结果以复制数组

转载 作者:行者123 更新时间:2023-12-03 22:19:57 26 4
gpt4 key购买 nike

我有以下代码,假设有一些 Sequelize 模型 UserfindQuery这意味着返回我一行:

import { from } from 'rxjs';
import sequelize from './database.js'; // Database connection

let sql = "SELECT * FROM users WHERE id = $1";

let searchUser = sequelize.query(sql);
let searchUser$ = from(searchUser);

searchUser$.subscribe(console.log);

我期望它给我的是 Observable<Array>它发出一个包含结果的数组。

问题

它向我发出一个数组,其中包含两个数组,包含相同的值:
[
[ {id: "someid", name: "John", age: 12} ],
[ {id: "someid", name: "John", age: 12} ]
]

期望值
[ {id: "someid", name: "John", age: 12} ]

如何修复我对 sequelize 的使用,使其仅返回一组结果?如何避免其重复结果?

最佳答案

出现重复结果的原因是因为Sequelize returns both the results of your SQL query and the metadata results .在某些情况下,您使用的 SQL 引擎也会将结果作为元数据返回。

您要做的是防止 Sequelize 将元数据返回给您。

Sequelize 模型使用引用

In cases where you don't need to access the metadata you can pass in a query type to tell sequelize how to format the results. For example, for a simple select query you could do:


sequelize.query("SELECT * FROM `users`", { type: sequelize.QueryTypes.SELECT})
.then(users => {
// We don't need spread here, since only
// the results will be returned for select queries
})

TL;DR 如何防止 Sequelize 返回元数据?

除了传递您可能在查询选项中绑定(bind)的任何参数之外,还将类型说明符添加到您的查询选项中:
import { from } from 'rxjs';
import sequelize from './database.js'; // Database connection

let sql = "SELECT * FROM users WHERE id = $1";

let queryOptions = {
bind: [],
type: sequelize.QueryTypes.SELECT
}

let searchUser = sequelize.query(sql, queryOptions);
let searchUser$ = from(searchUser);

searchUser$.subscribe(console.log);

关于rxjs - 将 sequelize Promise 转换为可观察的结果以复制数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54418277/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com