【发布时间】:2020-11-28 03:41:16
【问题描述】:
我在这段代码中遇到了一些问题。问题是当我从messages.ejs 发布消息时,MongoDB 集合在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});
我想不是所有的信息都填写在请求中,所以会出现这样的问题,尽管在更新对话集合时甚至不应该添加头像、类型、子组等字段。
let query = { id: data.conv_id };
//Check if such conversation exists
Conversation.find({}, query).count((err, cnt) => {
if(cnt > 0) {
//If IDs were found, add new messages to the existing conversation
Conversation.updateOne(query, {
"$push" : {
messages: [
{
body: data.body,
author: data.author_name,
author_id: data.author_id,
author_avatar: data.author_avatar,
attachments: attachments,
added: data.added
}
]
}
}, (err) => {
if(err) {
throw err;
return;
} else {
console.log('Conversation has been updated with new messages');
return;
}
});
} else {
//If there's no such IDs, create a new conversation
let newMessage = new Conversation({
id: data.conv_id,
type: data.type,
avatar: "defaultConv.png",
subgroup: 'all',
users: data.users,
messages: [
{
body: data.body,
author: data.author_name,
author_id: data.author_id,
author_avatar: data.author_avatar,
attachments: attachments,
added: data.added
}
]
});
newMessage.save((err) => {
if(err) {
console.log(err);
return;
} else {
console.log('Conversation has been created');
return;
}
});
}
});
【问题讨论】:
-
我认为 find 函数希望查询排在第一位?
Conversation.find(query) -
我已经解决了这个问题,请看下面的答案
标签: javascript node.js database mongodb socket.io