Home > Net >  How to fetch all data only from mongoose with Nodejs
How to fetch all data only from mongoose with Nodejs

Time:10-28

I am not able to fetch all the data from mongoose. When I tried to fetch data it create new collection name(signins) with empty, but singin collection already exists.

I don't understand what I am doing wrong here

Index.js File

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

mongoose
    .connect("mongodb://0.0.0.0:27017/signin")
    .then(() => console.log("MongoDB Connected"))
    .catch((err) => console.log(err));

const User = require("./models/signin");

app.use("/", (req, res) => {
    User.find({}, (err, data) => {
        if (err) throw new err();
        return res.json(data);
    });
});

app.listen(5500, () => console.log("Port Started on 5500"));

signin

const mongoose = require("mongoose");
const Schema = mongoose.Schema;

const loginSign = new Schema({
    email: { type: String, required: true },
    password: { type: String, required: true },
    date: { type: Date, default: Date.now },
});

module.exports = Users = mongoose.model("signin", loginSign);

enter image description here

enter image description here

CodePudding user response:

Mongoose will automatically "pluralize" the name of your collection from your model name.

So mongoose.model("signin", loginSign) is creating a collection named "signins".

From the documentation: https://mongoosejs.com/docs/models.html#compiling

The first argument is the singular name of the collection your model is for. Mongoose automatically looks for the plural, lowercased version of your model name.

Providing a third argument will use a collection name you specify, instead of the one mongoose creates. So in your case you could:

mongoose.model("signin", loginSign, "signin");

That said, having plural collection names is the standard, and encouraged.

  • Related