仅在尚不存在的情况下插入文档 [英] Insert document only if not already exists

查看:77
本文介绍了仅在尚不存在的情况下插入文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用

Subscription.create({ email: req.body.email }, (err, subscription) => {
  //
});

我在Mongoose模式中使email字段唯一,因此无法用同一封电子邮件创建多个文档.

I have made the email field unique in my Mongoose schema, so it's not possible to create multiple docs with same email.

但是我不在乎某个电子邮件是否已经存在,所以我现在不想收到重复的错误.仅当电子邮件不存在时如何插入,如果电子邮件不存在却不通知用户,该如何创建?

But I don't care whether a certain email already exists, so I don't want a duplicate error as I receive now. How can I insert only if the email doesn't exist already and not create if it does exist, but not tell the user?

我认为最好的做法是不告诉用户数据库中是否已经存在该电子邮件,因为它可以用来测试电子邮件是否与该站点相关联.似乎并没有太大问题,但是出于隐私方面的考虑,我还是认为最好还是不要说.

I assume it's best practice not to tell the user if the email already exists in the database, since it can be used to test whether an email is associated with the site. It doesn't seem very problematic, but I still think it's better not to tell due to privacy concerns.

推荐答案

在猫鼬中,您可以使用pre函数.

In mongoose you can use the pre function.

var schema = new Schema(..);
schema.pre('save', function(next) {
  // Check if the mail exists. If it does, just throw an exception
  // If not, just create the thing using next.
  next();
});

在调用保存函数时,您应该小心捕捉异常.我相信这可以完成工作.

You should be careful to catch the exception and when you call the save function. I believe this will do the work.

这篇关于仅在尚不存在的情况下插入文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆