How to create item if not exists and return an error if exists

后端 未结 2 1781
北恋
北恋 2021-01-27 03:49

I\'m writing alexa skill and would like to check if user exists in MongoDB. My code works but I don\'t know how to define situation if user is already in a database :(

E

2条回答
  •  野的像风
    2021-01-27 04:40

    It sounds like what you really want is a unique key constraint and not an upsert.

    The unique key can be set in [mongoose] with either the schema field options:

    const s = new Schema({ name: { type: String, unique: true }});
    

    or by the index method:

    Schema.path('name').index({ unique: true });
    

    If an attempt is made to create a document that already has an entry for that key then an error will be thrown:

    NOTE: violating the constraint returns an E11000 error from MongoDB when saving, not a Mongoose validation error.

提交回复
热议问题