MongoDB和Mongoose:无法使用.populate()填充用户的帖子

问题描述 投票:1回答:1

我已经搜索了这个网站几天,通过这个主题的许多不同但相似的问题无济于事。

这就是我想要发生的事情。用户登录并且其帖子自动链接到用户集合。最后我想把帖子链接到它发布到的个人资料,但我还没到那里。这是我到目前为止所尝试过的。

在用户架构中:

const UserSchema = new Schema({
    posts: [{
        type: Schema.Types.ObjectId,
        ref: 'posts'
    }],
    firstName: {
        type: String,
        required: true
    },
    lastName: {
        type: String,
        required: true
    },
    ...
});

module.exports = User = mongoose.model('users', UserSchema);

在Post Schema中:

const PostSchema = new Schema({
    user: {
        type: Schema.Types.ObjectId,
        ref: 'users'
    },
    text: {
        type: String,
        required: true
    },
    name: {
        type: String
    },
    ...
});

module.exports = Post = mongoose.model('posts', PostSchema);

在我的用户api中,这是我如何签署用户并尝试填充用户的帖子:

const User = require('../../models/User');

router.post('/login', (req, res) => {
    const { errors, isValid } = validateLoginInput(req.body);

    // Check Validation
    if (! isValid) {
        return res.status(400).json(errors);
    }

    const email = req.body.email;
    const password = req.body.password;

    // Find user by email
    User.findOne({ email })
        .populate('posts')
        .then(user => {
            if (! user) {
                errors.email = 'User not found';
                return res.status(400).json(errors);
            }

            // Check password
            bcrypt.compare(password, user.password).then(isMatch => {
                if (isMatch) {
                    // User Matched
                    // Create JWT Payload
                    const payload = {
                        id: user.id,
                        firstName: user.firstName,
                        lastName: user.lastName,
                        name: user.firstName + ' ' + user.lastName,
                        avatar: user.avatar,
                        posts: user.posts

                    };

                    jwt.sign(
                        payload,
                        keys.secretOrKey,
                        { expiresIn: 3600 }, (err, token) => {
                        res.json({
                            success: true,
                            token: 'Bearer ' + token,
                            payload
                        });
                    });

                } else {
                    errors.password = 'Password is incorrect';
                    return res.status(400).json(errors);
                }
            });
    });
});

在帖子api中,这是帖子的提交方式:

router.post('/', passport.authenticate('jwt', { session: false }), (req, res) => {
    const { errors, isValid } = validatePostInput(req.body);

    if (! isValid) {
        // Return errors with 400 status
        return res.status(400).json(errors)
    }

    const newPost = new Post({
        text: req.body.text,
        name: req.body.name,
        avatar: req.body.avatar,
        user: req.user.id
    });

    newPost.save().then(post => res.json(post));
});

目前,我所看到的只是一个空数组,没有错误。我已经在这个上旋转了几天,所以任何帮助都会受到赞赏。谢谢!

mongodb mongoose
1个回答
0
投票

我想您忘记将新帖子的_id保存到用户模型,以便populate()可以查找要填充的帖子:

newPost.save().then(post => {
    User.update({ _id: req.user.id }, { $push: { posts: post._id }}, (err) => {
        res.json(post));
    });
});
© www.soinside.com 2019 - 2024. All rights reserved.