Sunday 14 May 2017

Mongoose: How to prevent mongodb to save duplicate email records in database

I want to make the key email unique across that collection but i cant getting this working, here is my server code.

// Create a schema
var userSchema = new mongoose.Schema({
    email: { type: String, required: true},
    password: String
});

var userModel = mongoose.model("user", userSchema);

router.post('/postuser', (req, res) => {
    console.log('Requested data to server: ' + JSON.stringify(req.body._user));
var user = new userModel({
    email: req.body._user.email,
    password: req.body._user.password
});
// user.isNew = false;
user.save((err, data) => {
    console.log('Analyzing Data...');
    if(data) {
        console.log('Your data has been successfully saved.');
        res.json(data);
}
else {
  console.log('Something went wrong while saving data.');
  console.log(err);
  res.send(err);
}

})
});

Note: I also try email: { type: String, required: true, unique: true} but its not working.



via Ahmer Ali Ahsan

No comments:

Post a Comment