skip to Main Content

mongodb database example

I included the database schema and I’m trying to fetch the products in the *products * array using Postman.
Here is the base URL: http://localhost:5002/api/v1/store

Also, the backend is fine and connected so http://localhost:5002/api/v1/store?name=Apple would return the first document.

Thanks

Edit: I’ve added the code that gets executed on endpoint api/v1/store

storeDao.js

let store;

export default class StoreDAO {
  static async injectDB(conn) {
    if (store) {
      return;
    }
    try {
      store = await conn.db(process.env.RESTREVIEWS_NS).collection("store");
    } catch (e) {
      console.error(
        `Unable to establish a collection handle in storeDAO: ${e}`
      );
    }
  }

  static async getStore({ filters = null, page = 0, storePerPage = 20 } = {}) {
    let query;
    if (filters) {
      if ("name" in filters) {
        query = { $text: { $search: filters["name"] } };
      } else if ("zipcode" in filters) {
        query = { zipcode: { $eq: filters["zipcode"] } };
      }
    }

    let cursor;

    try {
      cursor = await store.find(query);
    } catch (e) {
      console.error(`Unable to issue find command, ${e}`);
      return { storeList: [], totalNumStore: 0 };
    }

    const displayCursor = cursor.limit(storePerPage).skip(storePerPage * page);

    try {
      const storeList = await displayCursor.toArray();
      const totalNumStore = await store.countDocuments(query);

      return { storeList, totalNumStore };
    } catch (e) {
      console.error(
        `Unable to convert cursor to array or problem counting documents, ${e}`
      );
      return { storeList: [], totalNumStore: 0 };
    }
  }
}

store.controller.js

import storeDao from "../dao/storeDAO.js";

export default class StoreController {
  static async apiGetStore(req, res, next) {
    const storePerPage = req.query.storePerPage
      ? parseInt(req.query.storePerPage, 10)
      : 20;
    const page = req.query.page ? parseInt(req.query.page, 10) : 0;

    let filters = {};
    if (req.query.zipcode) {
      filters.zipcode = req.query.zipcode;
    } else if (req.query.name) {
      filters.name = req.query.name;
    }

    const { storeList, totalNumStore } = await storeDao.getStore({
      filters,
      page,
      storePerPage,
    });

    let response = {
      store: storeList,
      page: page,
      filters: filters,
      entries_per_page: storePerPage,
      total_results: totalNumStore,
    };
    res.json(response);
  }
}

2

Answers


  1. Chosen as BEST ANSWER

    Just fixed it, turns out you have to add another filter in storeDAO and the storecontroller

    storeDao.js

    let query;
    if (filters) {
      if ("name" in filters) {
        query = { $text: { $search: filters["name"] } };
      } else if ("zipcode" in filters) {
        query = { zipcode: { $eq: filters["zipcode"] } };
      } else if ("products" in filters) {
        const product = filters["products"];
        query = { products: { $elemMatch: { name: product } } };
      }
    }
    

    store.controller.js

    let filters = {};
    if (req.query.zipcode) {
      filters.zipcode = req.query.zipcode;
    } else if (req.query.name) {
      filters.name = req.query.name;
    } else if (req.query.products) {
      filters.products = req.query.products;
    }
    

    And then you can call it in your frontend. The documentation for querying arrays from MongoDB in your application can be found here: https://www.mongodb.com/docs/manual/reference/operator/query-array/


  2. In the current implementation, if the filters parameter is null, the function does not assign a value to the query variable. As a result, when the function tries to execute the query store.find(query), it will throw an error because the query variable is undefined. Try initializing query as an empty object.

     let query = {};
    

    final code for getStore method should look like this.

    static async getStore({ filters = null, page = 0, storePerPage = 20 } = {}) {
        let query = {};
        if (filters) {
          if ("name" in filters) {
            query = { $text: { $search: filters["name"] } };
          } else if ("zipcode" in filters) {
            query = { zipcode: { $eq: filters["zipcode"] } };
          }
        }
    
        let cursor;
    
        try {
          cursor = await store.find(query);
        } catch (e) {
          console.error(`Unable to issue find command, ${e}`);
          return { storeList: [], totalNumStore: 0 };
        }
    
        const displayCursor = cursor.limit(storePerPage).skip(storePerPage * page);
    
        try {
          const storeList = await displayCursor.toArray();
          const totalNumStore = await store.countDocuments(query);
    
          return { storeList, totalNumStore };
        } catch (e) {
          console.error(
            `Unable to convert cursor to array or problem counting documents, ${e}`
          );
          return { storeList: [], totalNumStore: 0 };
        }
      }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search