writingdeveloper
writingdeveloper

Reputation: 1076

How to query all data with mongoose Schema?

My website is developed as Node.js, Express.js, and MySQL. Recently, I have been working on converting MySQL DB to MongoDB, and there is a problem connecting MongoDB data.

I am using Mongoose, MongoDB ODM, and I read Mongoose's document and wrote the same code, but I cannot get the data. Maybe there is a problem with schema setting or DB connection process, so I wonder how to solve it.

The data structure in my DB consists of the following. MongoDB Compass

[index.js]

const db = require("../lib/db");
let User = require('../lib/models/userModel');
router.get("/", function (req, res, next) {
  console.log(`HOME ROUTE!`);
  User.find(),  // Find All data in user collection
    function (err, result) {
      if (err) return handleError(err);
      console.log(result);
    }
});

[userModel.js]

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
mongoose.set('useCreateIndex', true)

const userSchema = new Schema({
  _id: String,
  login: String,
  id: {
    type: Number,
    unique: true
  }
});
console.log('Module Success')

module.exports = mongoose.model("User", userSchema);

[db.js]

const mongoose = require('mongoose');
mongoose.connect(process.env.MONGO_URI, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

let db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // we're connected!
  console.log('DB Connected');
});

module.exports = db;

[Log when connecting to Home route]
enter image description here

As you can see, there are no results printed on the console, but there are no error phrases, so I don't know where the problem occurs.

Upvotes: 0

Views: 2726

Answers (1)

Puneet Singh
Puneet Singh

Reputation: 3543

The way you are calling User.find is not correct, Check below, updated working index.js

const db = require("../lib/db");
let User = require('../lib/models/userModel');
router.get("/", function (req, res, next) {
  console.log(`HOME ROUTE!`);
  User.find({}, function (err, result) {
      if (err) return handleError(err);
      console.log(result);
    })
});

Upvotes: 1

Related Questions