1

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}`));
chachacha
  • 328
  • 1
  • 2
  • 10

3 Answers3

2

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".

mysl
  • 1,003
  • 2
  • 9
  • 19
  • This worked thank you. I used an empty schema and ran it and it returned documents. Then I was able to define a schema and query documents. – monkeyjumps Feb 18 '20 at 05:55
1

I am not sure if this is the only record of that type of json in your data base. But If you want to send if follwing a get request you first need to get the document.

// @route GET
app.get("/", (req, res) => res.send(db.restaurants.find()));
// may be something like
app.get('/', (req, res) => {
    mongooseModel.find({query}, (err, result) => {
    res.send(result);
  });
})

Depending on what mongoose.model defenition you have and how you would like to find it you could use find (return an array) findById (return single document) or findOne and a query.

S. Kuiter
  • 99
  • 9
1

here an example how to create you model:

//restaurant.js
const mongoose = require('mongoose');

const RestaurantSchema = new mongoose.Schema({
      name: { type: String, required: true },
      address: { type: String, required: true },
      description:{ type: String, required: true }
      //just you add how you need your schema
});

module.exports = mongoose.model('Restaurant', RestaurantSchema);

and here your updated code

const express = require("express");
const mongoose = require("mongoose");
const Restaurant = require("./restaurant.js");

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) => {
   Restaurant.find({}, (err, docs) => {
     res.send(docs);
   });
);

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

app.listen(port, () => console.log(`Server started on port ${port}`));
Nemer
  • 667
  • 1
  • 6
  • 10