所以我正在学习mongodb和mongoose,我正在尝试制作一个项目/任务应用程序,这是ProjectModel:
const projectSchema = new mongoose.Schema(
{
name: {
type: String,
required: true,
unique: true,
trim: true,
lowercase: true,
},
grp: {
type: String,
required: true,
trim: true,
lowercase: true,
},
tasks: {
type: [taskSchema],
},
createdAt: { type: Date, default: Date.now },
},
{
toObject: { virtuals: true },
toJSON: { virtuals: true },
}
);
projectSchema.virtual('tasksCount').get(function () {
return this.tasks.length;
});
当请求数据时,它运行:
getAllProjects = async (req, res) => {
try {
const query = await Project.find().select({tasks: -1});
const projects = query.;
console.log(projects);
res.status(200).send({
status: 'sucess',
data: {
projects,
},
});
} catch (error) {
res.status(400).send({
status: 'fail',
msg: `error info : ${error}`,
});
}
};
问题是:我得到这个错误:TypeError:无法读取未定义的属性“length”。它来自虚拟属性('tasksCount'),所以当我取消选择('tasks')属性时,虚拟属性似乎无法计算,我希望有人有办法取消选择'tasks'并且仍然能够发送'tasksCount'。
1条答案
按热度按时间tp5buhyn1#
您可以按照此代码