简体   繁体   English

MongoDB .find 问题 NodeJS

[英]MongoDB .find problems NodeJS

When I attempt the code below, I just get an empty return from MongoDB....当我尝试下面的代码时,我只是从 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?我如何在我的代码中解决这个问题,或者在 Mongo 更新中这是一个要求?

By default, mongoose pluralizes the name of the model when you call mongoose.model() to determine the collection name.默认情况下,当您调用mongoose.model()来确定集合名称时,mongoose 会将模型的名称复数化。 In your first example, it will be looking in the tests collection for documents.在您的第一个示例中,它将在tests集合中查找文档。

In the second example, you specify that the name of the collection should be test , which is why the behavior is different.在第二个示例中,您指定集合的​​名称应为test ,这就是行为不同的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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