猫鼬填充功能什么也不做

时间:2019-09-15 08:46:56

标签: node.js mongoose

我正在使用.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();
} );

此发布路由具有auth中间件,该中间件仅检查用户是否已登录,然后将用户返回为req.user。它将创建一个具有名称,描述和ID(这是用户ID,以后可以查询的用户ID)的新任务。

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

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

感谢您的帮助

1 个答案:

答案 0 :(得分:1)

我在本地计算机上尝试了以下代码,并且可以正常工作。我删除了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);
        });
      })
      })
  });