猫鼬填充函数不执行任何操作



我正在使用.populate((,但是它无法正常工作。"用户"有一个名为"任务"的字段,它是一个数组,这就是我要存储创建的任务的内容。目前,该任务有一个"作者"字段,即用户ID,因此我可以检索由特定用户编写的任务。但是我也希望它显示在用户的数组中。

用户架构:

const UserSchema = new mongoose.Schema( {
name: {
type: String,
required: true
},
password: {
type: String,
required: true,
trim: true,
unique: true
},
email: {
type: String,
required: true,
unique: true,
validate( value ) {
if ( !validator.isEmail( value ) ) {
throw new Error( "Email is unvalid" );
}
}
},
tasks: [ {
type: mongoose.Schema.Types.ObjectID,
ref: "Task"
} ],
tokens: [ {
token: {
type: String
}
} ]
} );
const User = mongoose.model( "User", UserSchema );
module.exports = User;

任务架构:

const taskSchema = mongoose.Schema( {
name: {
type: String,
required: true,
unique: true
},
description: {
type: String
},
completed: {
type: Boolean,
default: false
},
author: {
type: mongoose.Schema.Types.ObjectID,
ref: "User"
}
} );
const Task = mongoose.model( "Task", taskSchema );
module.exports = Task;

创建任务:

router.post( "/api/tasks", auth, async ( req, res ) => {
const task = await new Task( { name: req.body.name, description: req.body.description, author: req.user._id } );
task.save( ( error ) => {
if ( error ) {
throw new Error( error );
}
if ( !error ) {
Task.find( {} ).populate( "author" ).exec( ( error, tasks ) => {
if ( error ) {
throw new Error( error );
}
} );
}
} );
res.status( 200 ).send();
} );

此 post 路由有一个身份验证中间件,它只检查用户是否已登录,然后将用户返回为 req.user。它创建一个具有名称,描述和ID的新任务(这是用户ID,我可以在将来查询(。

但是,在此特定用户数据库中,运行此任务后"tasks"数组为空,但任务已创建,并且任务的用户ID为"作者"。

我这样做的顺序是否错误,也许保存得太早了?

谢谢你的帮助

我在本地机器上尝试了下面的代码,它正在工作。我删除了auth中间件,所以现在req.user.authorreq.body.author也删除了错误处理,这是我可以提供的最小代码:

app.post("/api/tasks", (req, res) => {
const task = new Task( { 
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
author: req.body.author,
});
task.save(err => {
User.findByIdAndUpdate(req.body.author, { $push: {tasks: task._id}}, {new: true}, (err, foundUser) => {
Task.find({}).populate( "author" ).exec( ( error, foundTasks ) => {
return res.status(201).send(foundTasks);
});
})
})
});

最新更新