【问题标题】:mongoose populate function does nothing猫鼬填充功能什么都不做
【发布时间】: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._idreq.body._id
  • 不,req.user._id 来自我的中间件,即当前登录的用户,存储为 req.user。按预期工作

标签: node.js mongoose


【解决方案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);
        });
      })
      })
  });

【讨论】:

  • 嗯,创建这个任务后用户的tasks数组还是空的
  • 在保存到数据库之前尝试控制台日志req.body.namereq.body.descriptionreq.user._id
  • 工作正常。任务“作者”字段是用户的 ID。所以我已经能够将它们连接在一起,但是用户在数组中没有那个任务
  • 什么都没解决?我的意思是这已经奏效了。但是用户仍然没有“tasks”数组中的任务
  • 您可能需要在更改架构后删除数据库
猜你喜欢
  • 2020-01-17
  • 2016-02-26
  • 2018-02-12
  • 2015-07-13
  • 2016-10-10
  • 2015-05-29
  • 1970-01-01
  • 2015-07-13
相关资源
最近更新 更多