Mongo和Mongoose-.find()返回不同的值



在这里Stumped,它应该是非常简单的东西。

我有一个MERN堆栈应用程序,它没有像预期的那样从mongo中查找数据。

在前端,我发布并更新文档。我登录到Mongo CLI,可以看到我保存的数据。

但是对于Node应用程序,Mongoose不会返回完整的文档。

这是我获取文档的途径——我甚至尝试测试获取Everything。

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_id,
});
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,
required: true,
default: {},
},
course_id: {
type: String,
required: true,
},
});
module.exports = CourseProgress = mongoose.model(
"CourseProgressSchema",
CourseProgressSchema
);

有人能帮我弄清楚为什么猫鼬只返回了文件的一部分而不是整个文件吗?

Mongoose默认情况下不显示空对象。为了获得这些,您必须在创建模式时将minimize标志设置为false

const CourseProgressSchema = new Schema(
{
user_email: {
type: String,
required: true,
},
course_progress: {
type: Object,
required: true,
default: {},
},
course_id: {
type: String,
required: true,
},
},
{ minimize: false }
);

最新更新