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.