问题描述
在这里难住了,它应该是非常简单的事情。
我有一个 MERN 堆栈应用程序,它没有按预期从 mongo 中找到数据。
我在前端发布和更新文档。我登录到 Mongo CLI,可以看到我保存的数据。
但是对于 Node 应用程序,Mongoose 不会返回完整的文档。
router.get("/",async (req,res) => {
const user_email = req.query.user_email;
const course_id = req.query.course_id;
const test = await CourseProgressSchema.find({
_id: "60acfd1c969cac0bd3a213a8",});
console.log(test);
try {
let course_progress;
if (user_email && course_id) {
course_progress = await CourseProgressSchema.findOne({
user_email,course_id,});
if (!course_progress) {
const newCourseProgress = new CourseProgressSchema({
user_email,});
course_progress = await newCourseProgress.save();
}
} else if (user_email && !course_id) {
course_progress = await CourseProgressSchema.find({ user_email });
} else if (course_id && !user_email)
course_progress = await CourseProgressSchema.find({ course_id });
else {
res.json({ error: "Not Found." });
}
console.log(course_progress);
res.json({ success: course_progress });
} catch (error) {
console.log(error);
res.json({
error: "Soemthing went wrong when getting current course progress.",});
}
});
course_progress 被安慰/返回为:
[0] [
[0] {
[0] _id: 60acfd1c969cac0bd3a213a8,[0] user_email: 'nickisyourfan@icloud.com',[0] course_id: '60acfcfe969cac0bd3a213a7',[0] __v: 0
[0] }
[0] ]
但是如果我访问 mongo cli 并使用 db.courseprogressscchemas.find().pretty()
它返回更新的文档:
{
"_id" : ObjectId("60acfd1c969cac0bd3a213a8"),"user_email" : "nickisyourfan@icloud.com","course_id" : "60acfcfe969cac0bd3a213a7","__v" : 0,"course_progress" : {
"60acfca1969cac0bd3a213a5" : {
}
}
}
这是我的架构 - 没什么特别的:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const CourseProgressSchema = new Schema({
user_email: {
type: String,required: true,},course_progress: {
type: Object,default: {},course_id: {
type: String,});
module.exports = CourseProgress = mongoose.model(
"CourseProgressSchema",CourseProgressSchema
);
谁能帮我弄清楚为什么猫鼬只返回文档的一部分而不是整个文档?
解决方法
Mongoose 默认不显示空对象。为了获得这些,您必须在创建架构时将 minimize
标志设置为 false
。
const CourseProgressSchema = new Schema(
{
user_email: {
type: String,required: true,},course_progress: {
type: Object,default: {},course_id: {
type: String,{ minimize: false }
);