Not sure why I am not getting any results from a GET call I am making with Postman.
Here is my server.js:
const express = require("express");
const mongoose = require("mongoose");
const app = express();
const uri =
"mongodb+srv://[REDACTED]:[REDACTED]@cluster0.d5zbb.mongodb.net/?retryWrites=true&w=majority";
async function connect() {
try {
await mongoose.connect(uri);
console.log("Connected to MongoDB");
} catch (error) {
console.error(error);
}
}
mongoose.set("strictQuery", true);
connect();
const userRouter = require("./routes/users");
app.use("/users", userRouter);
app.listen(8000, () => {
console.log("Server started on port 8000");
});
Here is my models/Users.js:
const mongoose = require("mongoose");
const userSchema = new mongoose.Schema({
_id: mongoose.SchemaTypes.ObjectId,
firstName: String,
lastName: String,
phoneNumber: String,
isVendor: Boolean,
});
module.exports = mongoose.model("User", userSchema, "users");
And here is my users.js route:
const express = require("express");
const router = express.Router();
const User = require("../models/User");
router.get("/", async (req, res) => {
try {
const users = await User.find({});
console.log(users);
res.json(users);
} catch (error) {
res.sendStatus(500);
console.log(error.message);
}
});
module.exports = router;
In MongoDB, I have a users
collection under a database and here is sample data:
{"_id":{"$oid":"63f90e2c00f411064f0415a8"},"firstName":"John","lastName":"Customer","phoneNumber":"1111111111","isVendor":false}
The endpoint I am hitting is http://localhost:8000/users
but it always console logs an empty array. Literally any kind of help is truly appreciated. Thanks!
2
Answers
After suffering through debugging MongoDB, I needed to specify the database name in the Mongo uri string. Here is the post that helped me: https://www.mongodb.com/community/forums/t/mongodb-create-a-test-database/211636/2
Your folder naming and import are mismatched for the model.
Also, you have to specify your database name and then the collection name while connecting to MongoDB.
connection string: "mongodb://127.0.0.1:27017/your_database_name";
Apart from this everything is fine with this code.
Documentation Link:
https://www.mongodb.com/docs/manual/reference/connection-string/