使用 Mongoose 避免在 MongoDB 上重复

avoid duplicates on MongoDB using Mongoose

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

这就是我现在尝试做的方式名称和 phone 数字是强制性的,而且名称必须是唯一的,否则它会引发错误。

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

})

如果我发送缺少名称或号码的 post 请求,它已经抛出错误,但似乎没有进行唯一值验证。

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

参考validation

Validators are not run on undefined values. The only exception is the required validator.

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

您可以这样做,而不是直接将请求正文传递给查询。

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/

终于找到了一个包,可以让我避免在 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);