【问题标题】:avoid duplicates on MongoDB using Mongoose使用 Mongoose 在 MongoDB 上避免重复
【发布时间】:2021-05-15 12:43:51
【问题描述】:

您好,我是 MongoDB 和 Moongoose 的新手,我试图避免我的 api 用户在 Mongo 数据库中存储重复的联系人姓名,但似乎它根本不起作用。

这就是我现在尝试这样做的方式,名称和电话号码是强制性的,而且名称必须是唯一的,否则会引发错误。

const contactSchema = new mongoose.Schema({
        name: {
            type: String,
            required: true,
            unique: true
        },
        number: {
            type: Number,
            required: true
        }
    });

app.post('/api/persons', (request, response) => {

    const body = request.body;

    const person = new Contact({
        name: body.name,
        number: +body.number
    });

    person.save()
        .then(saved => {
            response.json(saved);
        })
        .catch(error => {
            return response.status(400).json({
                error: 'content missing'
            });
        });

})

如果我发送一个缺少名称或编号的发布请求,它已经引发了一个错误,但似乎没有得到唯一值验证。

【问题讨论】:

    标签: node.js mongodb express mongoose mongoose-schema


    【解决方案1】:

    唯一验证的错误很奇怪所以你可以使用unique-validator插件,之后当你发送一个缺少名称或号码的post请求时,错误是关于required: true

    参考validation

    验证器不在undefined 值上运行。唯一的例外是必需的验证器。

    【讨论】:

      【解决方案2】:

      因为您的数据库中的两个字段(名称和编号)都是必需的。

      您可以执行以下操作,而不是将请求正文直接传递给查询。

      const name = body.name;
      const number = body.number;
      
      if(!name || !number) {
           //  Return response saying either of the fields is empty.
           //  It's not a good practice to hit the DB with undefined values.
      }
      
      let personDetails = {
           "name": name,
           "contact": contact
      };
      
      const person = new Contact(personDetails);
      

      关于唯一验证,您可以使用Mohammad Yaser Ahmadi 建议的唯一验证器插件,或者您可以进行数据库调用以检查名称和号码是否唯一,然后点击保存方法,如果这对您来说是可行的数据库。

      如果您希望将两个字段 namenumber 组合为唯一,您可以按如下方式创建复合索引:

      contactSchema.index({ name: 1, number: 1 }, { unique: true });
      

      您可以在此处阅读有关复合索引的更多信息:https://docs.mongodb.com/manual/core/index-compound/

      【讨论】:

        【解决方案3】:

        终于找到了一个包,可以让我避免在 Mongo 上重复条目。我按照文档说明使用了这个包:

        https://github.com/blakehaswell/mongoose-unique-validator#readme

        这是我必须编写的代码:

        const uniqueValidator = require('mongoose-unique-validator');
        
        const contactSchema = new mongoose.Schema({
                name: {
                    type: String,
                    required: true,
                    unique: true
                },
                number: {
                    type: Number,
                    required: true
                }
            });
        
            contactSchema.plugin(uniqueValidator);
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-08-24
          • 2016-07-24
          • 2016-07-30
          • 2020-05-18
          • 2019-10-06
          • 2017-01-31
          • 2019-10-15
          相关资源
          最近更新 更多