0

Need to a save new record even if one record already exists with status false in unique schema using mongoose node js. I have one record along with {status:false} by updating status true to false while deleting that record. Now i try to add a new record. but new record is not crated. because i have apply unique: true in mongoose schema. I need to apply unique : true, but same time need to create new record if it's status false for exist one. So can anyone give some suggestion

Mongoose, nodejs with mongoose-beautiful-unique-validator

//schema model
     var userSchema = new mongoose.Schema({
          userName: {
         type: String,
         required: true,
         unique: true
     })

 //save user function inside module export function
 const user= mongoose.model('userSchema');
 user.userName = fields.username;
 user.save((err, doc) => {
                 if (!err){
                     res.send(true);
                 } else {
                     console.log(err);

                     return;
                 }

              })

Expected result:

  [
   {_id: 12345, userName: 'Uday', status:false},
   {_id: 67894, userName: 'Uday', status:true}
  ]

Actual result: I got duplicate error When i try to save name with Uday with status: true

 [
   {_id: 12345, userName: 'Uday', status:false},
 ]
dimitris tseggenes
  • 3,031
  • 2
  • 16
  • 23
uday s
  • 63
  • 8
  • If my understanding is correct, what you need is composite key on username and status. Please see this ref : https://stackoverflow.com/questions/16061744/mongoose-how-to-define-a-combination-of-fields-to-be-unique you have to create index on these two fields and mark unique true also remove the unique : true from current schema – Vikash_Singh Apr 04 '19 at 18:26

3 Answers3

2

If you want duplicate entries for the username then you need to remove unique: true from schema design, because you can't save the same username twice in same collections.

And if your requirement is just to update status so you can use update query instead of save/insert.

Mohammad Zeeshan
  • 825
  • 1
  • 9
  • 20
0

Your id is alway unique in mongodb. Without same id you only can insert data but same id its not possible.

Anupam
  • 201
  • 2
  • 4
  • 11
0

Drop the required attribute from your Schema, then you could pass a callback to pre('save', callback) that checks 2 things:

  1. Does the username already exists (just check the return from Model.find({username: usernameToCheck}, callback));
  2. In your callback, check for the status attribute, if its false then throw an exception, else save your document.
Moad Ennagi
  • 1,058
  • 1
  • 11
  • 19