我是新来的我有两个集合=>User和Task。
每个用户可以有多个任务,但每个任务只能有一个用户。
用户架构:
const UserSchema = new Schema({
name: {
type: String, // type of the variable
required: [true, "Please provide a name"], // this variable must be filled
},
tasks: [
{
type: mongoose.Schema.ObjectId,
ref: "Task",
},
],
});
字符串
TaskSchema:
const TaskSchema = new Schema({
title: {
type: String, // type of the variable
required: [true, "Please provide a title"], // this variable must be filled
},
user: {
type: mongoose.Schema.ObjectId,
required: true,
ref: "User", // give reference to the user model
},
});
型
下面的代码列出了所有任务数据及其用户:
await Task.find().populate("user");
型
但是当我列出User数据时,task属性为空:
await User.find().populate(tasks");
型
创建任务体:
{
"title": "Task 1",
"user": "64afb6943c764b68ad9c1f61"
}
型
我的问题是,当我添加新任务时,我是否也应该将任务ID添加到MongoDB上的用户任务属性中?因为我无法通过这种方式读取用户的任务。
1条答案
按热度按时间lvjbypge1#
是的。你应该
push()
新的task
到user.tasks
数组。字符串
完整的工作示例:
型
日志:
型