无法使用$ push更新Mongo DB对话集合

时间:2020-08-07 19:14:50

标签: javascript node.js database mongodb socket.io

这段代码有点麻烦。问题是,当我从// @desc Process the count form // @route POST /session/create router.post('/session/create', async (req, res) => { req.body.user = req.user.id await Count.save(err, req.body) => { if(err) { next(err); } const itemID = req.body._id; res.redirect('/new-page' + itemID); } }); 发布消息时,在messages.ejs中MongoDB Collection不会得到更新,一切正常。

profile.ejs

profile.ejs

socket.emit('newMessage', {body: message_text, type: "Single", conv_id: users[0].id + "_" + users[1].id, users: users, author_name: message__author_name.val(), author_avatar: message__author_avatar.val(), author_id: message__author_id.val(), added: message__date});

messages.ejs

我想并不是所有的信息都填充在请求中,所以存在这样的问题,尽管在更新“对话”集合时甚至不应该添加诸如头像,类型,子组之类的字段。
            socket.emit('newMessage', {body: message_text, 
                                        conv_id: urlParams.get('id'),
                                        author_name: '<%= sessionUser.name %>' + ' ' + '<%= sessionUser.lastname %>',
                                        author_avatar: '<%= sessionUser.avatar %>',
                                        author_id: '<%= sessionUser.id %>',
                                        added: message__date});

1 个答案:

答案 0 :(得分:0)

我已经解决了这个问题。这都是由于我不注意将带有get方法的URL对象放在何处引起的。

messages.ejs文件中是:

    // When User has clicked send button
    // Sending Message
    let queryString = window.location.search;
    const urlParams = new URLSearchParams(queryString);
    let urlId = urlParams.get('id');

    sendMessage__btn.click(() => {

        ...

        socket.emit('newMessage', {body: message_text, 
                                        conv_id: urlId,
                                        author_name: '<%= sessionUser.name %>' + ' ' + '<%= sessionUser.lastname %>',
                                        author_avatar: '<%= sessionUser.avatar %>',
                                        author_id: '<%= sessionUser.id %>',
                                        added: message__date});

代替:

    sendMessage__btn.click(() => {
        
        // When User has clicked send button
        // Sending Message
        let queryString = window.location.search;
        const urlParams = new URLSearchParams(queryString);
        let urlId = urlParams.get('id');

        ...

        socket.emit('newMessage', {body: message_text, 
                                        conv_id: urlId,
                                        author_name: '<%= sessionUser.name %>' + ' ' + '<%= sessionUser.lastname %>',
                                        author_avatar: '<%= sessionUser.avatar %>',
                                        author_id: '<%= sessionUser.id %>',
                                        added: message__date});

结果,变量urlId未被更新,并且返回null或不正确的id