【问题标题】:Mongoose populate function does not populate猫鼬填充功能不填充
【发布时间】: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 用户时,我得到的只是有关用户的信息,但任务数组仍然是空的。

我是不是按错误的顺序做某事,或者错过了一个步骤?

感谢您的宝贵时间

【问题讨论】:

    标签: node.js mongoose


    【解决方案1】:

    这不是自动完成的。也就是说,Mongoose 不会推送到用户的tasks 数组来保存他们的任务 ID。您需要手动执行此操作:

    user.tasks.push(task);
    

    更多详情请访问Refs to children

    【讨论】:

    • 啊,我以为这就是 populate 所做的。您能否向我解释一下 populate 的作用?我会查看您提供的文档,谢谢!
    • Populate 将从属性中取出 _id(s),并将其替换为基于该 _id(s) 从其他集合加载的完整文档。在您的情况下,用户的 tasks 在数据库中仍然是空的,因此 Mongoose 认为没有要加载的文档。
    猜你喜欢
    • 2015-07-13
    • 2016-10-10
    • 2018-02-12
    • 2015-07-13
    • 2020-01-16
    • 2021-05-06
    • 2019-06-05
    • 2019-09-16
    相关资源
    最近更新 更多