此问题在此处已有答案:
Mongoose always returning an empty array NodeJS(7个答案)
七年前就关门了。
请查找app.js的代码var express = require('express'),routes = require('./routes');
var mongoose = require('mongoose');
var app = module.exports = express.createServer();
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(app.router);
app.use(express.static(__dirname + '/public')); });
app.configure('development', function(){
app.use(express.errorHandler({ dumpExceptions: true, showStack: true }));
});
app.configure('production', function(){
app.use(express.errorHandler()); });
// Routes
app.get('/', routes.index);
app.listen(3000, function(){
console.log("Express server listening on port %d in %s mode",
app.address().port, app.settings.env); });
mongoose.connect('mongodb://localhost/mydb', function (error) {
if (error) {
console.log(error);
}
});
var Schema = mongoose.Schema;
var UserSchema = new Schema({
first_name: String,
last_name: String,
email: String
});
// Mongoose Model definition
var User = mongoose.model('users', UserSchema);
app.get('/', function (req, res) {
res.send("<a href='/users'>Show Users</a>");
});
app.get('/users', function (req, res) {
User.find({}, function (err, docs) {
res.json(docs);
});
});
app.get('/users/:email', function (req, res) {
if (req.params.email) {
User.find({ email: req.params.email }, function (err, docs) {
res.json(docs);
});
}
});
Mongodb正在运行,并且在mydb中和下面的集合内存在文档{“_id”:对象ID(“562101187941 ab 21 a444 c286”),“名字”:“u1”,“姓氏”
:“u1”,“电子邮件”:“an@ii.com“}
但是当我运行nodejs app.js并连接到http://localhost:3000/users时,它显示[]而不是数据库中的数据。请帮助
1条答案
按热度按时间ljsrvy3e1#
实际上,你的集合应该命名为“users”,这样mongoose才能找到它。Mongoose通常用复数名称保存集合,在模型名称后面加上“s”。因为你的模型名称已经是复数了,所以应该命名为“users”。