diff --git a/app/model/ChatData.js b/app/model/ChatData.js new file mode 100644 index 0000000000000000000000000000000000000000..0930038c7ca2ffcd38c9e9d551217e7fd4b7496f --- /dev/null +++ b/app/model/ChatData.js @@ -0,0 +1,66 @@ +class ChatData { + constructor () { + this.mongoose = require('mongoose') + this.mongoose.connect('mongodb://localhost/wbd3_chat') + + this.chatSchema = new this.mongoose.Schema({ + participant_ids: [Number], + chats: [{ + owner_id: Number, + content: String + }] + }) + this.ChatModel = this.mongoose.model('Chat', this.chatSchema) + } + + addChat (senderId, receiverId, content) { + let participantIds = [ senderId, receiverId ] + participantIds.sort() + + let chat = { + owner_id: senderId, + content: content + } + + this.ChatModel.findOneAndUpdate( + { participant_ids: participantIds }, + { $push: { chats: chat } }, (err, done) => { + if (err) { + console.error(err) + } + + if (!done) { + let chat = new this.ChatModel({ + participant_ids: participantIds, + chats: [{ + owner_id: senderId, + content: content + }] + }) + + chat.save() + } + }) + } + + findChat (firstParticipantId, secondParticipantId) { + let participantIds = [ firstParticipantId, secondParticipantId ] + participantIds.sort() + + this.ChatModel.findOne({ participant_ids: participantIds }, function (err, result) { + if (err) { + return console.error(err) + } + + if (result) { + let chats = result.chats + + chats.forEach(function (chat) { + console.log(chat) + }) + } + }) + } +} + +module.exports = ChatData