【发布时间】:2020-01-17 05:50:12
【问题描述】:
我有一个用户架构和一个任务架构。 (如下所示)
当我创建任务时,任务的“作者”字段会填充用户 ID。但是,即使在运行 .populate("tasks") 之后,该用户的任务数组也不会在其中获得任何值。
我尝试过先搜索用户,然后再填充,反之亦然。尝试查看 mongoose 文档,但不确定它是如何工作的。
用户架构
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, "users" );
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, "tasks" );
module.exports = Task;
Task的创建(req.user._id来自中间件)
router.post( "/api/tasks", auth, async ( req, res ) => {
const task = await new Task( {
_id: new mongoose.Types.ObjectId(),
name: req.body.name,
description: req.body.description,
author: req.user._id
} );
task.save( ( error ) => {
if ( error ) {
throw new Error( error );
}
if ( !error ) {
User.find( {} ).populate( "tasks" ).exec( ( error, tasks ) => {
if ( error ) {
throw new Error( error );
}
} );
}
} );
res.send( task );
} );
当我搜索用户,然后填充任务字段,然后 console.log 用户时,我得到的只是有关用户的信息,但任务数组仍然是空的。
我是不是按错误的顺序做某事,或者错过了一个步骤?
感谢您的宝贵时间
【问题讨论】: