0

I have read a lot of similar issues talking for pluralization on the model's name by default on mongoose. Though it doesn't seem to work on this case. The problem is that it returns an empty array. My local mongoDB contains 2 documents in the "userData" collection that they look like this:

{
        "_id" : ObjectId("5dcd0582587ac600ec9323a5"),
        "name" : "John",
        "surname" : "Doe",
        "team" : "CE",
        "project" : "Project1",
        "id" : "2"
}

Then this is my model User.js:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({
    name: 'String',
    surname: 'String',
    team: 'String',
    project: 'String',
    id: 'String'
}, { collection: 'UserData' });

module.exports = mongoose.model('user', userSchema);

and this is my routes userRoutes.js:

const mongoose = require('mongoose');
const User = mongoose.model('user');

module.exports = (app) => {

  app.get(`/`, async (req, res) => {
    let users = await User.find();
    return res.status(200).send(users);
  });

  app.post(`/user`, async (req, res) => {
    let user = await User.create(req.body);
    return res.status(201).send({
      error: false,
      user
    })
  })

  app.put(`/user/:id`, async (req, res) => {
    const { id } = req.params;
    let user = await User.findByIdAndUpdate(id, req.body);
    return res.status(202).send({
      error: false,
      user
    })

  });

  app.delete(`/user/:id`, async (req, res) => {
    const { id } = req.params;
    let user = await User.findByIdAndDelete(id);
    return res.status(202).send({
      error: false,
      user
    })

  })

}

Finally this is my starting point index.js:

const express = require('express');
const mongoose = require('mongoose'); /*-- Import the mongoose module --*/
const bodyParser = require('body-parser');
require('./models/User');

const app = express();

mongoose.Promise = global.Promise;
mongoose.connect('mongodb://localhost:27017/users', { useUnifiedTopology: true, useNewUrlParser: true })  
  .then(() => console.log('Database Connection Succesful'))
  .catch(err => console.log('Database Connection Error0'));

var db = mongoose.connection;

db.on('error', console.error.bind(console, 'MongoDB connection error:'));
app.use(bodyParser.json());

require('./routes/userRoutes')(app);

if (process.env.NODE_ENV === 'production') {
  app.use(express.static('client/build'));

  const path = require('path');
  app.get('*', (req, res) => {
    res.sendFile(path.resolve(__dirname, 'client', 'build', 'index.html'))
  })

}

const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
  console.log(`app running on port ${PORT}`)
});

Then my return is an empty array []. Any help appreciated.

0

2 Answers 2

1

In your schema code, you need to define field types like name: String instead of name: "String".

Your schema must be like this:

const mongoose = require("mongoose");
const { Schema } = mongoose;

const userSchema = new Schema(
  {
    name: String,
    surname: String,
    team: String,
    project: String,
    id: String
  },
  { collection: "UserData" }
);

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

Also you already created user model, so in userRoute there is no need to do like this:

const User = mongoose.model('user');

You just need to correctly import User model like this in userRoute.

const User = require("../models/User"); // you can change the path if it is not correct

Lastly to enable the json for post data, you need to add this line to your index.js:

app.use(bodyParser.json()); 

With these changes, you can create a user with this url http://localhost:3000/user using a json body like this:

{
    "name": "John",
    "surname": "Doe",
    "team": "CE",
    "project": "Project1",
    "id": "2"
}

This will give a result like this:

{
    "error": false,
    "user": {
        "_id": "5dce7f8c07d72d4af89dec57",
        "name": "John",
        "surname": "Doe",
        "team": "CE",
        "project": "Project1",
        "id": "2",
        "__v": 0
    }
}

At this point you will have a collection UserData.

And when you send a get request to http://localhost:5000 url, you will get the users like:

[
    {
        "_id": "5dce75a91cbb4e5f7c5ebfb3",
        "name": "John",
        "surname": "Doe",
        "team": "CE",
        "project": "Project1",
        "id": "2",
        "__v": 0
    }
]
Sign up to request clarification or add additional context in comments.

7 Comments

@FotiosTragopoulos you must create a user
Then you will be able to get users
The first code block in the question is one of the users, I added it there as an example of the db.userData.find() response on the mongoDB shell.
@FotiosTragopoulos please create a new user with the new code, and try to get users
|
0

Try to require your model like this const User = require('{your path}'); May be you need to use ‘User’ not ‘user’ when you define your model module.exports = mongoose.model('User', userSchema);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.