【发布时间】:2022-11-19 03:55:22
【问题描述】:
我正在尝试查询 mongoDB 数据库。
我已经声明了我的架构:
const mongoose = require('mongoose');
const CosmeticSchema = new mongoose.Schema({
code: String,
url: String,
creator: String,
----------------- omitted -----------------
});
module.exports = mongoose.model('Cosmetics_DB_original', CosmeticSchema, 'comestics_collections');
我需要它,我正在尝试查询字段代码:
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.'
}));
});
};
这会导致 500 状态代码,但控制台显示 结果:空
发出 getAll 请求返回状态码 200 但正文只是 []
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.'
}))
});
};
并制作 findById 返回状态代码 200 但在主体上为 null。
我在 stackoverflow 上发现的所有问题最终都会让发布问题的用户意识到他们查询的是错误的数据库,但我很确定我的问题是正确的。集合名称为 comestics_collection 和 comestics_collection秒产生相同的结果。请帮忙
【问题讨论】:
-
为什么要同时使用回调函数和承诺来处理
findOne?我很确定当您使用回调时,这不会再返回承诺。 -
不清楚为什么会出现错误。空结果不会引发异常。如果需要错误状态码,应该单独处理
-
@KonradLinkowski 老实说,我对此一无所知,猫鼬文档总是给我留下比我一开始想的更多的问题。如果您碰巧知道一个很好的基础教程,那就太好了。
-
@MaximSharai 看我上面的评论