You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.13 17:10:24