简体   繁体   English

检查包含具有特定值的字段的文档是否存在的最佳方法是什么 - Firestore?

[英]Whats the best way to check for the existence of a document which contains a field with a specific value - Firestore?

I want to check if a field nam has a specific value and return a boolen if true(or check by something else - whatever).我想检查一个字段nam是否具有特定值,如果为真则返回一个布尔值(或通过其他方式检查 - 无论如何)。 Here is my code which actually does check but still returns something (some autogenerated stuff from the server) and if I check for null of course it will never be null.这是我的代码,它确实检查但仍然返回一些东西(一些来自服务器的自动生成的东西),如果我检查null当然它永远不会是 null。

So, whats the easiest and best way to do this?那么,最简单和最好的方法是什么? And is it better to do it server-side?在服务器端做会更好吗? PS I want to inform the user that a field with this value was found! PS 我想通知用户找到了具有此值的字段!

Here is my current code:这是我当前的代码:

var type_of_vendor = db().collection(this.state.vendor_type).where('nam', '==', this.state.vendor_name);
type_of_vendor.get()
    .then((user) => {
        if (user.exists) {
            this.state.error = true;
            let errorMessage = 'error message';
            this.setState({ errorMessage: errorMessage });
        } else {
            this._signUpVendorvalidateHandler();
        }
    });

Your code looks fine to me.你的代码对我来说看起来不错。 The only think I'd change is add .limit(1) to the query, so that you never retrieve more than 1 document, even if there are multiple matches.我唯一想改变的是将.limit(1)添加到查询中,这样即使有多个匹配项,您也永远不会检索超过 1 个文档。

Doing this server-side is possible with either Cloud Functions, or on a server you already control.可以使用 Cloud Functions 或在您已经控制的服务器上执行此服务器端操作。

If you do this on the server, you will only have to return whether the document exists (a boolean), instead of the entire document.如果您在服务器上执行此操作,则只需返回文档是否存在(布尔值),而不是整个文档。 So you're saving some bandwidth there.所以你在那里节省了一些带宽。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM