从MongoDB获取JSON数据返回空数组而非实际数据求助
问题描述
我通过连接字符串连接名为myflixDB2的MongoDB数据库,想给单页应用的主视图组件获取电影标题列表,但数据库明明有数据,调用/movies接口却始终返回空数组,就像集合是空的一样。我已经检查过连接字符串,甚至新建了第二个数据库尝试,还是解决不了,求技术帮助。
models.js
const mongoose = require("mongoose"); const bcrypt = require('bcrypt'); let movieSchema = mongoose.Schema({ Title: {type: String, required: true}, Description: {type: String, required: true}, Genre: { Name: String, Description: String }, Director: { Name: String, Bio: String }, Actors: [String], ImagePath: String, Featured: Boolean }); let userSchema = mongoose.Schema({ Username: {type: String, required: true}, Password: {type: String, required: true}, Email: {type: String, required: true}, Birthday: Date, FavoriteMovies: [{ type: mongoose.Schema.Types.ObjectId, ref: "Movie" }] }); userSchema.statics.hashPassword = (password) => { return bcrypt.hashSync(password, 10); }; userSchema.methods.validatePassword = function(password) { return bcrypt.compareSync(password, this.Password); }; let Movie = mongoose.model("movies", movieSchema); let User = mongoose.model("user", userSchema); let Users = mongoose.model("users", userSchema); // Add this line module.exports = { Movie, User, Users, // Add this line };
index.js
const express = require('express'); const mongoose = require('mongoose'); const bodyParser = require('body-parser'); const cors = require('cors'); const Models = require('./models.js'); const { Movie } = Models; const mongoURI = 'mongodb+srv://username:password@cluster0.dlxbnnp.mongodb.net/myflixDB2?retryWrites=true&w=majority&appName=Cluster0'; // Connect to MongoDB with error handling mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => console.log('MongoDB connected')) .catch(err => console.error('MongoDB connection error:', err)); const app = express(); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); app.use(cors({ origin: 'http://localhost:63239' })); // Define routes app.get('/', (req, res) => { res.send('Welcome to the best movie search app ever! (Maybe😁)'); }); app.get('/movies', async (req, res) => { try { const movies = await Movie.find(); console.log('Fetched movies:', movies); // Logging fetched movies res.json(movies); } catch (err) { console.error(err); res.status(500).json({ error: 'Internal Server Error' }); } }); // Add more routes as needed const port = process.env.PORT || 8080; app.listen(port, '0.0.0.0', () => { console.log('Listening on Port ' + port); });
解决方案
1. 检查集合名称匹配
Mongoose默认会将模型名称转换为小写复数形式作为集合名。你的代码中mongoose.model("movies", movieSchema),对应的集合名是movies(因为模型名已经是复数小写)。
- 登录MongoDB管理界面(Atlas或本地客户端),确认
myflixDB2数据库中存储电影数据的集合名称确实是movies(MongoDB集合名区分大小写,注意不要和Movie/Movies混淆)。 - 如果数据库里的集合名是自定义名称(比如
Movie),需要在Schema定义时显式指定集合名:let movieSchema = mongoose.Schema({ // 原有字段定义 }, { collection: "你的实际集合名" }); // 新增这行指定集合
2. 验证数据库连接准确性
在mongoose连接成功后,添加代码打印当前连接的数据库名称,确认是否连接到了正确的myflixDB2:
mongoose.connect(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true }) .then(() => { console.log('MongoDB connected'); console.log('当前连接的数据库:', mongoose.connection.db.databaseName); // 新增验证 }) .catch(err => console.error('MongoDB connection error:', err));
确保电影数据确实存储在myflixDB2中,而非其他数据库。
3. 核对字段名一致性
检查数据库中电影文档的字段名是否与Schema定义完全匹配(比如Schema中是Title首字母大写,数据库里不能是title)。虽然这不会导致返回空数组,但如果字段完全不匹配也可能影响结果,建议确认。
4. 测试查询逻辑
暂时修改/movies接口的查询语句,添加明确的条件(比如查询某部存在的电影名称),验证是否能返回结果:
app.get('/movies', async (req, res) => { try { // 替换成你数据库中存在的电影标题 const movies = await Movie.find({ Title: "你的电影标题" }); console.log('Fetched movies:', movies); res.json(movies); } catch (err) { console.error(err); res.status(500).json({ error: 'Internal Server Error' }); } });
内容的提问来源于stack exchange,提问作者Jordan Ballard
相关产品推荐
相关产品推荐

