【问题标题】:Mongoose populate猫鼬居住
【发布时间】:2016-12-27 02:58:04
【问题描述】:
var estadoSchema = Schema({
    estado_nome: String
});

var cidadeSchema = Schema({
    cidade_nome: String,
    estado_reference: [{ type: Schema.Types.ObjectId, ref: 'Estados'}]
});

这是设计模式,在数据库中包含以下内容时,我遇到了与模式状态相关的问题,即在插入时重复,理想的情况是仅在不存在时创建一个模式状态,并关联模式城市通过引用的状态。在创建模式之后。

Estado.create(req.body)
          .then(function(estado){
                Cidade.create({cidade_nome: cidade, cidade_reference: [estado._id]})
                      .then(function(cidade){
                            res.status(201).json(cidade);
                      }, function(erro){
                            res.status.json(erro)
                      });  
                res.status(201).json(estado);
          }, function(erro){
                res.status.json(erro)
          });

【问题讨论】:

    标签: mongoose mongoose-populate


    【解决方案1】:

    estado_nome 中尝试 unique : trueestadoSchema 中。这将确保仅当新状态不存在且没有重复时才会创建新状态。

    var estadoSchema = Schema({
        estado_nome: {
            type :String,
            unique : true
        }
    });
    

    【讨论】:

      猜你喜欢
      • 2015-02-18
      • 1970-01-01
      • 2015-12-16
      • 1970-01-01
      • 1970-01-01
      • 2019-09-16
      • 2019-07-17
      • 2017-10-08
      相关资源
      最近更新 更多