Node.js操作MongoDB:查询返回null且状态码异常求助
MongoDB查询异常问题
问题现象
尝试查询MongoDB数据库时遇到以下异常:
- 调用
getByNum接口返回500状态码,但控制台打印Result : null - 调用
getAll接口返回200状态码,但响应体为空数组[] - 调用
findById返回200状态码,但响应体为null
已确认数据库和集合名称无误,尝试将集合名称改为comestics_collection或comestics_collections后结果一致,问题仍存在。
已定义的Schema
const mongoose = require('mongoose'); const CosmeticSchema = new mongoose.Schema({ code: String, url: String, creator: String, ----------------- 省略部分字段 ----------------- }); module.exports = mongoose.model('Cosmetics_DB_original', CosmeticSchema, 'comestics_collections');
查询接口代码
getByNum接口
const Note = require('./models/Cosmetic'); module.exports.getByNum = (event, context, callback) => { context.callbackWaitsForEmptyEventLoop = false; connectToDatabase() .then(() => { var movie="00037541" Note.findOne({"code":movie}, function (err, note) { if (err){ console.log(err) } else{ console.log("Result : ", note); } }) .then(note => callback(null, { statusCode: 200, body: JSON.stringify(note) })) .catch(err => callback(null, { statusCode: err.statusCode || 500, headers: { 'Content-Type': 'text/plain' }, body: 'Could not fetch the note.' })); }); };
getAll接口
module.exports.getAll = (event, context, callback) => { context.callbackWaitsForEmptyEventLoop = false; connectToDatabase() .then(() => { Note.find() .then(notes => callback(null, { statusCode: 200, body: JSON.stringify(notes) })) .catch(err => callback(null, { statusCode: err.statusCode || 500, headers: { 'Content-Type': 'text/plain' }, body: 'Could not fetch the notes.' })) }); };
数据库信息确认
数据库及集合名称截图:
内容的提问来源于stack exchange,提问作者sempre_em_pe
相关产品推荐
相关产品推荐

