【问题标题】:How to modify existing data or create new if doesn't exist in mongodb?如果 mongodb 中不存在,如何修改现有数据或创建新数据?
【发布时间】:2019-04-08 02:12:11
【问题描述】:

我在 mongodb 中创建了会话模型。在集合中,我想插入文档,每个文档必须有 user1、user2 和我要插入的对话数组。

对话架构:

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);

消息架构:

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, ... 那么我想检查任何 2 个用户之间是否存在对话让我们说 user1 和 user2 如果存在,那么只需 $push new message inside 对话,否则创建新对话并保持关于将消息添加到现有对话数组。我怎样才能在 mongodb 中做到这一点?

【问题讨论】:

  • 至少你必须上网搜索才能直接在这里提问
  • @AlokDeshwal 我不知道upsert 我搜索了很多但找不到。
  • 我只是在谷歌上复制并粘贴你的问题,我找到了答案,第一个结果
  • @AlokDeshwal 你能分享链接吗?
  • @AlokDeshwal 你能帮帮我吗-> stackoverflow.com/questions/53150727/…

标签: mongodb


【解决方案1】:

$push 和upsert: true

如果没有用户 X 和用户 Y 的对话,它将被更新插入。否则,它会将对话 $push 到现有文档。

Conversation.findOneAndUpdate(
  { user1 : 'X', user2: 'Y' }, 
  { $push : { conversations: ObjectIdOfMessage } },
  { upsert : true},
);

【讨论】:

  • 我正在使用对话模式填充消息模式,所以我需要在对话模式中导入消息模式吗?
  • 啊,如果你想保持当前模式,你必须 $push ObjectID of conversation。
  • 如果我使用你回答的代码,那么我会收到一个错误 -> upsert 预期的属性分配为什么会这样?
  • @fun小丑我改错顺序了,我更新了答案
猜你喜欢
  • 1970-01-01
  • 2021-02-09
  • 2022-01-12
  • 1970-01-01
  • 2021-09-13
  • 2019-11-30
  • 1970-01-01
  • 2015-10-09
相关资源
最近更新 更多