google-cloud-firestore - 如何将参数动态添加到 Firestore 查询并映射到对象
问题描述
将数据映射到对象并将其作为 promise/observable 返回,同时能够向查询添加动态/条件参数的推荐方法是什么。
在 getCompanies2 中,我可以动态地将参数添加到查询中,但我无法弄清楚如何将返回的数据映射到我的对象并将其作为 promise/observable 返回。
在 getCompanies 中,一切都按我的意愿工作,但如果我有要添加的动态查询参数,我必须复制代码(如下所示)。
注意: convertDocTimeStampsToDate 只是按照它说的去做。我已将其排除在外以减小代码部分的大小。
getCompanies(searchText: string, useWhereActive: boolean): Observable<Company[]> {
if (useWhereActive) {
return this.db.collection('companies', ref => ref
.orderBy('name').startAt(searchText).endAt(searchText + '\uf8ff')
.where('active', '==', true)
)
.snapshotChanges()
.pipe(
map(snaps => convertSnaps<Company>(snaps)),
first()
);
} else {
return this.db.collection('companies', ref => ref
.orderBy('name').startAt(searchText).endAt(searchText + '\uf8ff')
)
.snapshotChanges()
.pipe(
map(snaps => convertSnaps<Company>(snaps)),
first()
);
}
}
getCompanies2(searchText: string, useWhereActive: boolean) {
let query = this.db.collection('companies').ref
.orderBy('name').startAt(searchText).endAt(searchText + '\uf8ff');
if (useWhereActive) {
query.where('active', '==', true);
}
query.get().then(querySnapshot => {
const results = this.convertDocuments<Company>(querySnapshot.docs);
console.log(results);
});
}
convertDocuments<T>(docs) {
return <T[]>docs.map(doc => {
return {
id: doc.id,
...doc.data()
};
});
}
export function convertSnaps<T>(snaps) {
return <T[]>snaps.map(snap => {
const data = convertDocTimeStampsToDate(snap.payload.doc.data());
return {
id: snap.payload.doc.id,
...data
};
});
}
解决方案
I got it to work like below, I guess I am still getting my head around promises.
Any better solutions will be accepted though as I am still learning and don't know if this is the best method.
getCompanies2(searchText: string, useWhereActive: boolean) {
let query = this.db.collection('companies').ref
.orderBy('name').startAt(searchText).endAt(searchText + '\uf8ff');
if (useWhereActive) {
query.where('active', '==', true);
}
return query.get().then(querySnapshot => {
return this.convertDocuments<Company>(querySnapshot.docs);
});
}
推荐阅读
- mysql - MySQL 查询辅助将过滤应用于两列
- jquery - 向 <input type="text" > 添加一个 ID 属性,该属性使用 Javascript/$Jquery 动态分配和 api
- llvm - 关于llvm教程中Kaleidoscope的编译问题
- javascript - Javascript拆分返回未定义
- fortran - ifort 编译器中“浮动无效”的含义
- azure - 订阅 Azure 消息队列的应用程序类型是什么?
- sqlite - SQLite 嵌套查询最大
- angular - 在 ngx 翻译中使用文件
- java - Spark scala模式未在加载时强制执行
- ruby-on-rails - Rails 5.2.2 Heroku 总是返回 app[web.1]: FATAL -- NameError (uninitialized constant AuthenticateUser::JsonWebToken)