【问题标题】:How to create an array of objects with default values?如何创建具有默认值的对象数组?
【发布时间】:2022-01-07 04:37:56
【问题描述】:

如何创建具有默认值的对象数组?

const schema = new mongoose.Schema({
    login: {type: String, unique: true, required: true},
    password: {type: String, required: true},
    chatlist: [
        {
            channelname: {type: String, default: "frontend"},
            channelid: {type: String, default: "619a6bfe5b0931f1e5dbaf2c"}
        },
        {
            channelname: {type: String, default: "backend"},
            channelid: {type: String, default: "619a71002954ba23a951bb8f"}
        },
        {
            channelname: {type: String, default: "devops"},
            channelid: {type: String, default: "619d69c190a85a40893b6522"}
        },
    ]
})

上面的代码不起作用
当新用户注册时,我想在他的个人资料中添加默认聊天
接下来是用户必须能够从数据库中添加/删除聊天
我该怎么做?聊天需要是对象还是文档?

【问题讨论】:

    标签: mongodb mongoose mongoose-schema


    【解决方案1】:
    const schema = new mongoose.Schema({
        chatlist: {
          type: Array,
          defualt: []
        }
    }) 
    

    所以要在数组中有一个结构,我个人会使用错误处理使请求正确。

    更多信息请访问site

    【讨论】:

      【解决方案2】:

      没有找到任何好的解决方案,所以我就这样做了

      const schema = new mongoose.Schema({
          login: {type: String, unique: true, required: true},
          password: {type: String, required: true},
          chatlist: [{
              channelname: String,
              channelid: String
          }]
      })
      
      const user = await MONGO_user.create({
          login: login,
          password: hashPassword,
      })
      
      user.chatlist.push(
          {
              channelname: "frontend",
              channelid: "619a6bfe5b0931f1e5dbaf2c"
          }, {
              channelname: "backend",
              channelid: "619a71002954ba23a951bb8f"
          }, {
              channelname: "devops",
              channelid: "619d69c190a85a40893b6522"
          })
      
      await user.save()
      

      【讨论】:

      • 您的答案可以通过额外的支持信息得到改进。请edit 添加更多详细信息,例如引用或文档,以便其他人可以确认您的答案是正确的。你可以找到更多关于如何写好答案的信息in the help center
      猜你喜欢
      • 2015-12-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多