如何在不检查文档 ID 的情况下检查 Firestore 数据库中是否存在特定记录?

时间:2021-05-17 12:35:16

标签: node.js google-cloud-firestore

我在 firestore 数据库中存储的服务编号很少作为字段值。我在创建文档时给出了自动 ID。我需要检查数据库中是否存在特定的服务值。我是 nodejs 和 firestore 的新手。我尝试使用以下代码检查文档是否存在。有没有办法在不指定文档名称的情况下检查字段值?请在下面找到数据库的屏幕截图。

const express = require('express')
const functions = require('firebase-functions');
const bodyParser = require('body-parser')
const { WebhookClient } = require('dialogflow-fulfillment');
var admin = require("firebase-admin");

var serviceAccount = require("./config/carrental-pyq9-firebase-adminsdk-fuhho-938626a1a0.json");
const { error } = require('firebase-functions/lib/logger');

try {
    admin.initializeApp({
        credential: admin.credential.cert(serviceAccount),
        databaseURL: "https://carrental-pyq9.firebaseio.com"
    });
    console.log("connected to DB");
}
catch (error) {
    console.log("error here" + error);
}
var db = admin.firestore();


const app = express()
app.use(bodyParser.json())
const port = process.env.PORT || 3000

app.post('/dialogflow-fulfillment', (request, response) => {
     dialogflowFulfillment(request, response)
})
 
app.listen(port, () => {
    console.log(`Listeninng on port ${port}`)
})

    var  dialogflowFulfillment = async (request, response) => {
    const agent = new WebhookClient({request, response})

    async function sayHello(agent) {
        try {

            

            let roomtype = agent.parameters.roomtype;
            db.collection('bookroom').add({ roomtype: roomtype });
            const bookroomRef = db.collection('bookroom').where('roomtype', '==', 'tiny').get();
            

            if (bookroomRef.empty) {
                console.log('No matching documents.');
                return user; 
            }
            userDocRef.forEach(doc => {
                console.log(doc.id, '=>', doc.data());
            });


        }

        catch (e) {
            console.log("error occured");
        }
    }
       

    let intentMap = new Map();
    intentMap.set("bookroom", sayHello)
    agent.handleRequest(intentMap)

}

enter image description here

错误信息如下:

  PS C:\xampp\htdocs\nodeproject> node index.js
{"severity":"WARNING","message":"Warning, FIREBASE_CONFIG and GCLOUD_PROJECT environment variables are missing. Initializing firebase-admin will fail"}
connected to DB
Listeninng on port 3000
(node:16628) UnhandledPromiseRejectionWarning: Error: No handler for requested intent
    at WebhookClient.handleRequest (C:\xampp\htdocs\nodeproject\node_modules\dialogflow-fulfillment\src\dialogflow-fulfillment.js:327:29)
    at dialogflowFulfillment (C:\xampp\htdocs\nodeproject\index.js:67:11)
    at C:\xampp\htdocs\nodeproject\index.js:28:6
    at Layer.handle [as handle_request] (C:\xampp\htdocs\nodeproject\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\xampp\htdocs\nodeproject\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (C:\xampp\htdocs\nodeproject\node_modules\express\lib\router\route.js:112:3)
    at Layer.handle [as handle_request] (C:\xampp\htdocs\nodeproject\node_modules\express\lib\router\layer.js:95:5)
    at C:\xampp\htdocs\nodeproject\node_modules\express\lib\router\index.js:281:22
    at Function.process_params (C:\xampp\htdocs\nodeproject\node_modules\express\lib\router\index.js:335:12)
    at next (C:\xampp\htdocs\nodeproject\node_modules\express\lib\router\index.js:275:10)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:16628) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:16628) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.

1 个答案:

答案 0 :(得分:1)

是的,您可以在不提供 documentID 的情况下进行检查:

try {
const bookroomRef = db.collection('bookroom');
const snapshot = await bookroomRef.where('servicenumber', '==', 'PassYourValue').get();
if (snapshot.empty) {
  console.log('No matching documents.');
  return;
}  

snapshot.forEach(doc => {
  console.log(doc.id, '=>', doc.data());
});

}
catch (e) {
   console.log(`Error occurred: ${e}`);
}

您可以查看here了解更多详情。

相关问题