我已经在mongodb中创建了会话模型。在集合中,我要插入文档,并且每个文档都必须具有要插入的user1,user2和对话数组。
conversationSchema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const ConversationSchema = new Schema({
user1: {
type: String,
required: true
},
user2: {
type: String,
required: true
},
conversations : [{ type: Schema.Types.ObjectId, ref: 'Message' }]
});
module.exports = mongoose.model('Conversation', ConversationSchema);
messageSchema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const MessageSchema = new Schema({
author: {
type: String,
required: true,
},
message: {
type: String,
required: true
},
date: {
type: Date,
default: Date.now
}
});
module.exports = mongoose.model('Message', MessageSchema);
现在从客户端,我将接收user1和user2,即用户名,这是字符串和两者之间的对话。现在,如果有多个用户说user1,user2,user3,...,那么我想检查是否有任何两个用户之间存在对话,让我们说user1和user2是否存在,然后在对话中仅$ push新消息,否则创建新对话并保持将消息添加到现有对话数组中。我如何在mongodb中做到这一点?
答案 0 :(得分:1)
$ push和upsert: true
如果没有用户X和用户Y的对话,则会对其进行升级。否则,它将把会话推送到现有文档。
Conversation.findOneAndUpdate(
{ user1 : 'X', user2: 'Y' },
{ $push : { conversations: ObjectIdOfMessage } },
{ upsert : true},
);