Search code examples
javascriptmongodbmongoosequeryingmongoimport

How to query imported json using Mongoose


I've uploaded a json file to MongoDB Atlas cluster (using mongoimport) and now I'm trying to display the data to localhost using express and mongoose.

I've gotten to a point where I can connect to the cluster but I'm struggling in fetching and displaying the data. Below is the code I have thus far. I'd like to query the database via Nodejs using mongoose as I do on the command line with Mongo shell. What am I missing here?

const express = require("express");
const mongoose = require("mongoose");

const app = express();

// DB config using Mongo Atlas
const uri = require("./config/keys").mongoURI;

// // Connect to Mongo
mongoose
  .connect(uri, { useNewUrlParser: true })
  .then(() => console.log("MongoDB Connected..."))
  .catch(err => console.log(err));


// @route GET
app.get("/", (req, res) => res.send(db.restaurants.find()));

const port = process.env.PORT || 5000;

app.listen(port, () => console.log(`Server started on port ${port}`));

Solution

  • First, initialize a model which Mongoose needs to query data. Since you've imported the data, you don't necessarily have to structure your schema.

    // restaurants.js
    const mongoose = require('mongoose');
    
    const RestaurantsSchema = new mongoose.Schema({});
    
    module.exports = mongoose.model('Restaurants', RestaurantsSchema)
    

    Then, import the schema 'Restaurants' into your main driver file and specify your query by chaining filters like so:

    // main.js
    const express = require("express");
    const mongoose = require("mongoose");
    const Restaurants = require("./restaurants");
    
    const app = express();
    
    // DB config using Mongo Atlas
    const uri = require("./config/keys").mongoURI;
    
    // Connect to Mongo
    mongoose
      .connect(uri, { useNewUrlParser: true })
      .then(() => console.log("MongoDB Connected..."))
      .catch(err => console.log(err));
    
    // @route GET
    app.get("/", (req, res) => {
      Restaurants.find()
        .where("filter1").gt(200)
        .where("filter2").equals("$$$")
        .where("filter3").nin(["Coffee"])
        .limit(100)
        .sort("sort1")
        .select("column1 column2 column3")
        .then(restaurants => res.json(restaurants))
        .catch(err => res.status(404).json({ success: false }));
    });
    
    const port = process.env.PORT || 5000;
    
    app.listen(port, () => console.log(`Server started on port ${port}`));
    

    You should fill in the applicable values for "filter", "sort", "column", "gt", "equals", "limit", and "nin".