当我尝试下面的代码时,我只从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");
}
})
但是,当我使用此代码时,它会返回我要查找的数据。。。。。为什么?我看过的其他教程都是这样操作的。
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");
}
})
我如何在我的代码中解决这个问题,或者是Mongo更新中的某个内容要求这样做?
默认情况下,当您调用mongoose.model((来确定集合名称时,mongoose会将模型的名称复数化。在您的第一个示例中,它将在tests
集合中查找文档。
在第二个示例中,您指定集合的名称应为test
,这就是行为不同的原因。