【问题标题】:Mongoose schema two fields as oneMongoose 架构两个字段合二为一
【发布时间】:2022-01-25 19:55:04
【问题描述】:

我想将 shopid 和 email 合并并保存在名为 combine 的新字段中。 应该如何编写它的模式,以便它自动保存在 db 中

  shopId: { type: String, required: true },
  id: { type: String, required: true },
  email: { type: String, required: true },
  firstname: { type: String, required: true },
  lastname: { type: String, required: true },
  _shopId: { type: mongooose.Schema.Types.ObjectId, ref: 'Shop', required: true },

  combined: shopid + email 
  
})

【问题讨论】:

    标签: mongodb mongoose mongoose-schema


    【解决方案1】:

    您无法从架构自动执行此操作。如果你想要那个“组合”字段,你需要将它定义为一个对象或一个字符串(如果你正在考虑像 ${email}${id} 这样的字符串):

    shopId: { type: String, required: true },
      id: { type: String, required: true },
      email: { type: String, required: true },
      firstname: { type: String, required: true },
      lastname: { type: String, required: true },
      _shopId: { type: mongooose.Schema.Types.ObjectId, ref: 'Shop', required: true },
      // In case you need a separation of your fields
      combined: { 
          email: {
              type: String,
              required: true
          },
          shopId:{
              type: String, 
              required: true 
          }
    }
      //In case you need that one combined string
      combined: {
          type String,
          required: true
      }
    

    然后在保存该文档时在逻辑中添加“组合”字段。

    【讨论】:

      【解决方案2】:

      mongodb 不能强制 combined 永远是 shopId + email;你总是可以在事后和update combined 字段中加入其他内容。我建议既节省一点空间,又将逻辑移到 agg 管道中,例如

      db.foo.aggregate([
        {$addFields: {combined: {$concat: [ "$shopId", "$email" ]} }}
      ]);
      

      或者为了更清楚也许

      db.foo.aggregate([
        {$addFields: {combined: {$concat: [ "$shopId", "-", "$email" ]} }}
      ]);
      

      【讨论】:

        猜你喜欢
        • 2014-09-16
        • 2017-06-23
        • 1970-01-01
        • 2023-03-14
        • 1970-01-01
        • 2012-05-15
        • 2021-12-07
        • 1970-01-01
        相关资源
        最近更新 更多