Home > database >  Node Express Mongo API return empty result set
Node Express Mongo API return empty result set

Time:09-25

I'm going to develop API using Node Express & Mongo.I have manually entered data to mongo db like below and when i try to get data from the db it shows me empty in postman.Here i have paste my project code for easy to figure out.

In the controller returned empty results.

enter image description here


my project structure looks like this

enter image description here

db.config.json

module.exports = {
//url: "mongodb://localhost:27017/TestDb"
url: "mongodb://localhost:27017/Users"
 };

server.js

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

const app = express();

var corsOptions = {
  origin: "http://localhost:8081"
};

app.use(cors(corsOptions));

// parse requests of content-type - application/json
app.use(express.json());

// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));

// simple route
app.get("/", (req, res) => {
  res.json({ message: "Welcome to Shopping List." });
});

require("./app/routes/user.routes")(app);
// set port, listen for requests
const PORT = process.env.PORT || 8080;
app.listen(PORT, () => {
  console.log(`Server is running on port ${PORT}.`);
});

const db = require("./app/models");
db.mongoose
  .connect(db.url, {
    useNewUrlParser: true,
    useUnifiedTopology: true
  })
  .then(() => {
    console.log("Connected to the database!");
  })
  .catch(err => {
    console.log("Cannot connect to the database!", err);
    process.exit();
  });

index.js

  const dbConfig = require("../config/db.config.js");

const mongoose = require("mongoose");
mongoose.Promise = global.Promise;

const db = {};
db.mongoose = mongoose;
db.url = dbConfig.url;
db.users = require("./user.model.js")(mongoose);
console.log(db.url);
module.exports = db;

user.contoller.js

const db = require("../models");
const User = db.users;

// Retrieve all Tutorials from the database.
exports.findAll = (req, res) => {

  User.find({ isAdmin: false })
  .then(data => {
    console.log("datanew" data); // <-- Empty returns here.. []
    res.send(data);
  })
  .catch(err => {
    res.status(500).send({
      message:
        err.message || "Some error occurred while retrieving user."
    });
  });
};

user.model.js

module.exports = mongoose => {
var schema = mongoose.Schema(
  {
  firstName: String,
  lastName: String,
  password: String,
  email:String,
  isAdmin:Boolean
  },
  { timestamps: true }
);

schema.method("toJSON", function() {
  const { __v, _id, ...object } = this.toObject();
  object.id = _id;
  return object;
});

const User = mongoose.model("user", schema);
return User;
  };

user.route.js

module.exports = app => {
const users = require("../controllers/user.controller.js");

var router = require("express").Router();

// Retrieve all Tutorials
router.get("/", users.findAll);

app.use('/api/users', router);
  };

CodePudding user response:

It appears you manually created your MongoDB collection. Users must be in small letters so from the MongoDB interface, change Users => users and you'll be set.

Also your DB connection uri should be:

module.exports = {
 url: "mongodb://localhost:27017/TestDb"
 };

TestDB is the database while users is the collection. Your uri must point to a db that your code will query collections in.

Your User Model This is just a slight change but you want to keep your code consistent. User should all be in capitalize form. MongoDB is smart to user plural and small caps automatically in the db.

module.exports = mongoose => {
var schema = mongoose.Schema(
  {
  firstName: String,
  lastName: String,
  password: String,
  email:String,
  isAdmin:Boolean
  },
  { timestamps: true }
);

schema.method("toJSON", function() {
  const { __v, _id, ...object } = this.toObject();
  object.id = _id;
  return object;
});

const User = mongoose.model("User", schema);
return User;
  };

CodePudding user response:

// Actually you can  remove
 index.js     
 db.config.js  files 

// *********
add in server.js
const express = require('express')
const mongoose  = require('monggose') 
const app = express()

mongoose.connect('mongodb://localhost/TestDb');

  • Related