【发布时间】:2021-03-14 00:17:23
【问题描述】:
我有以下用于跟踪习惯和用户进度的架构
习惯模式
const HabitSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
},
title: {
type: String,
required: true,
},
type: {
type: String,
enum: ["Goal", "Limit"],
default: "Goal",
required: true,
},
dateStarted: {
type: Date,
default: Date.now,
required: true,
},
});
PROGRESS SCHEMA:每次用户点击他们在给定时间段(日、周、月等)内完成了一个习惯时,就会为该时间段创建一个文档,以表明它已经完成。
const ProgressSchema = new mongoose.Schema({
habit: {
type: mongoose.Schema.Types.ObjectId,
ref: "Habit",
},
period: {
type: Date,
default: Date.now,
required: true,
},
value: {
type: Number,
default: 1,
required: true,
},
});
当我获得所有用户的习惯时,我还想获得每个习惯的所有进度文档。我想在返回之前加入这些对象。
这是我尝试过的:
let habits = await Habit.find({ user: req.user.id }).sort({
dateStarted: -1,
});
habits = await Promise.all(
habits.map(async (h, i) => {
try {
const progress = await Progress.find({ habit: h._id });
return { ...h, progress };
} catch (e) {
res.status(500).send("Server Error");
}
})
);
res.json({ habits });
这给出了错误:CastError: Cast to ObjectId failed for value "undefined" at path "_id" for model "Habit"
实现此目的的正确方法是什么?
【问题讨论】:
-
那里的
i是什么。此外,req.user.id不是 ObjectId 类型,因此会出现错误。所以你需要把那个 req.user.id 变成 ObjectId 类型,对吧? -
i只是habits中项目的索引,由.map()提供给回调函数。我应该澄清一下,req.user.id 不会导致 ObjectId 相关错误,它工作正常。Progress.find({ habit: h._id })是导致错误的原因。 -
该错误似乎与代码不符。听起来它试图将传递给
Habit模型构造函数的对象的_id字段转换为ObjectId。我没有在提供的 sn-p 中看到这种情况。您确定它发生在您怀疑的那一行(它可能会与破坏堆栈跟踪的异步代码有点混淆)? -
为什么不在单个查询中使用
$lookup来获取习惯和进度?
标签: node.js mongodb mongoose mongoose-schema