【发布时间】:2020-01-16 10:40:19
【问题描述】:
我正在使用 .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 路由有一个 auth 中间件,它只检查用户是否登录,然后将用户作为 req.user 返回。它创建一个包含名称、描述和 ID 的新任务(这是用户 ID,我以后可以查询)。
但是,在这个特定的用户数据库中,“tasks”数组在运行后是空的,但任务已创建,并且该任务的用户 ID 为“作者”。
我这样做的顺序是否错误,可能是保存得太早了?
感谢您的帮助
【问题讨论】:
-
将
type: mongoose.Schema.Types.ObjectID更改为type: mongoose.Schema.Types.ObjectId -
谢谢你的回复,但还是不行:/
-
还有
req.user._id到req.body._id -
不,req.user._id 来自我的中间件,即当前登录的用户,存储为 req.user。按预期工作