繁体   English   中英

猫鼬填充以获取用户的所有帖子返回空数组

[英]Mongoose Populate to get all posts by user returns empty array

我试图更好地了解Express.js,并试图创建一个简单的博客网站。

我的用户模型很简单:用户名,显示名和帖子数组。

const userSchema = new Schema({
    username: {
        type: String,
        required: true, 
        unique: true, 
        trim: true, 
        minlength: 3
    },
    displayname: {
        type: String,
        required: true,
        minlength: 1
    },
    posts: [{ type: Schema.Types.ObjectId, ref: 'Post' }]
}, {
    timestamps: true,
});

我的Post模型也是如此:内容和作者。

const postSchema = new Schema({
    body: {
        type: String,
        required: true,
        minlength: 1,
        maxlength: 140
    },
    author: { type: Schema.Types.ObjectId, ref: 'User', required: true }
});

我已经成功创建了一个新用户并发布:

[
  {
    "posts": [],
    "_id": "5d32c9474e28f66c08119198",
    "username": "Prince",
    "displayname": "The Artist",
    "createdAt": "2019-07-20T07:56:55.405Z",
    "updatedAt": "2019-07-20T07:56:55.405Z",
    "__v": 0
  }
]

[
  {
    "_id": "5d34af1ecae7e41a40b46b5a",
    "body": "This is my first post.",
    "author": "5d32c9474e28f66c08119198",
    "__v": 0
  }
]

这是我创建用户和发布信息的路线

//Create a user
router.route('/create').post((req, res) => {
    const username = req.body.username;
    const displayname = req.body.displayname;

    const newUser = new User({
        username, 
        displayname
    });

    newUser.save()
        .then(() => res.json('New user created!'))
        .catch(err => res.status(400).json(`Error: ${err}`));
});
//Create A Post
router.route('/create').post((req, res) => {
    const body = req.body.body;
    const author = req.body.author;
    const newPost = new Post({
        body,
        author
    });

    newPost.save()
        .then(() => res.json('Created new post!'))
        .catch(err => res.status(400).json(`Error: ${err}`));
});

我的方法来获取用户的所有帖子:

//Get all posts by user
router.route('/posts/:id').get((req, res) => {
    User.findById(req.params.id)
        .populate('posts')
        .exec((err, user) => {
            if(err) {
                res.status(400).json(`Error: ${err}`);
            } else {
                res.json(user.posts);
            }
        });
});

每当我查看来自/ users / posts /:id的响应时,该数组为空,但是我希望它被用户提供的ID所填充的帖子所填充吗? 我是否误解了人口的工作方式?

您需要将帖子ID添加到用户帖子列表中,以便猫鼬的填充正常工作。

router.post('/create' async (req, res) => {
    const body = req.body.body;
    const author = req.body.author;
    const newPost = new Post({
        body,
        author
    });
    try {
        const user = await User.findById(author);
        const post = await newPost.save()
        user.posts = user.posts.concat(post._id)
        await user.save()
        return res.json(post.toJSON())
    } catch (e) {
        return res.status(400).json(`Error: ${e}`));
    }
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM