elisciandrello
elisciandrello

Reputation: 107

MongoDB .find problems NodeJS

When I attempt the code below, I just get an empty return from MongoDB....

let express = require('express');
let mongoose = require('mongoose');
let cors = require('cors');
let bodyParser = require('body-parser');

let testSchema = new mongoose.Schema({
    username: String,
    name: {
        firstname: String,
        lastname: String,
    },
    email: String,
    employeeID: String
});

const testModel = mongoose.model('test', testSchema);

mongoose.connect('mongodb://localhost:27017/test', { useUnifiedTopology: true }, function(err, res) {
    if (err) console.log(err);
    else console.log('Connected to Mongo');
});

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cors());

const port = 5000;
const server = app.listen(port, () => {
    console.log('connected to port ' + port);
});

testModel.find({}).exec(function(err, res){
    if (!err) {
        console.log(res);
    }
    else {
        console.log("Error");
    }
})

BUT, when I use this code, it returns the data I'm looking for..... why?! Every other tutorial I have seen operates like the above.

let express = require('express');
let mongoose = require('mongoose');
let cors = require('cors');
let bodyParser = require('body-parser');

let testSchema = new mongoose.Schema({
    username: String,
    name: {
        firstname: String,
        lastname: String,
    },
    email: String,
    employeeID: String
});

const testModel = mongoose.model('test', testSchema, 'test');

mongoose.connect('mongodb://localhost:27017/test', { useUnifiedTopology: true }, function(err, res) {
    if (err) console.log(err);
    else console.log('Connected to Mongo');
});

const app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended: true
}));
app.use(cors());

const port = 5000;
const server = app.listen(port, () => {
    console.log('connected to port ' + port);
});

testModel.find({}).exec(function(err, res){
    if (!err) {
        console.log(res);
    }
    else {
        console.log("Error");
    }
})

How can I fix this in my code, or is it something within Mongo updates that this is a requirement?

Upvotes: 0

Views: 41

Answers (1)

Montgomery Watts
Montgomery Watts

Reputation: 4034

By default, mongoose pluralizes the name of the model when you call mongoose.model() to determine the collection name. In your first example, it will be looking in the tests collection for documents.

In the second example, you specify that the name of the collection should be test , which is why the behavior is different.

Upvotes: 1

Related Questions