Mongoose模型数据未在mongodb中更新

时间:2018-03-16 14:04:56

标签: node.js mongodb mongoose mongoose-schema mongoose-models

我是node.js和mongodb的新手。我正在使用express for rest-api。

我正在尝试创建一个用户可以发布和喜欢的API。我可以创建post API,问题在于类似API,用户可以点击“赞”按钮进行计数,当他再次单击“喜欢”按钮时,它将采用不同的方式并在后端更新相同的内容在我的情况下服务器(快递和mongodb)。

架构定义

module.exports = mongoose.model('posts', new Schema({ 
    post: { type: String, required: true },
    date: { type: Date, required: true, default: moment.now() },
    author: { type: String, required: true },
    authorId: {type: String, required: true},
    likes: {type: Object, required: true, default: []},
    likesCount: { type: Number, required: true, default: 0},
    dislikes: { type: Object, required: true, default: [] },
    dislikesCount: { type: Number, required: true, default: 0 },
    comments: { type: Object, required: true, default: [] },
    commentsCount: { type: Number, required: true, default: 0 }
}, { timestamps : { createdAt: 'created_at' , updatedAt: 'updated_at' } }));

代码:

    router.post('/post/likes', function(req, res) {
    if (!_.isEmpty(req.body.postId) && !_.isEmpty(req.body.user) && !_.isEmpty(req.body.userId)) {

        //Finding the post by Id
        Posts.findById(req.body.postId, function(err, posts) {

            if (err) {
                return res.send(500).json({
                    success: false,
                    msg: err
                });
            }

            if (posts !== null) {
                var user = {
                    userId: req.body.userId,
                    user: req.body.user
                };
                //Returns the matched obj if true
                //Returns undefined if false
                var alreadyLiked = _.find(posts.likes, function(obj) {
                    if (obj.userId === user.userId && obj.user === user.user) {
                        return true;
                    } else {
                        return false;
                    }
                });


                if (alreadyLiked === undefined) {
                    posts.likes.push(user);
                    posts.likesCount = posts.likes.length;

                    var updatedPost = new Posts(posts);
                    updatedPost.save(function(err, data) {
                        if (err) {
                            return err;
                        }
                        res.status(200).send({
                            success: true,
                            data: data,
                            message: 'You have liked the post!'
                        });

                    });

                } else {
                    //Removing the already liked user object from posts.likes
                    posts.likes = _.without(posts.likes, _.findWhere(posts.likes, user));
                    posts.likesCount = posts.likes.length;

                    posts.markModified('likesCount');
                    var reupdated = new Posts(posts);
                    reupdated.save(function(err, data) {
                        if (err) {
                            return err;
                        }
                        res.status(200).send({
                            success: true,
                            data: data,
                            message: 'You have unliked the post!'
                        });

                    });

                }
            } else {
                res.status(200).send({
                    success: false,
                    message: 'No post found!'
                });
            }


        });
    } else {
        res.status(400).send({
            success: false,
            message: 'Bad request value'
        });
    }
});

问题是,当我第一次喜欢这篇文章时,它完美无缺,并返回预期的响应。

img:liked-response-img

当我通过调用相同的API而不同于帖子时,它会返回一些意外的结果。不喜欢的用户将从喜欢的属性中移除,但计数仍然是' 1'如下面的img所示。我无法弄清楚为什么?有人可以指出我在哪里做错了什么。提前谢谢!

img:unliked-response-img

1 个答案:

答案 0 :(得分:0)

如何制作posts.save()posts.save().exec()而不是创建新的“复制”帖子并保存。