简体   繁体   中英

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM