I have the following scenario, my model with the following schema
var MySchema = new Schema({
name: {type: String, required: true, unique: true}
})
var MyModel = mongoose.model('MyModel', MySchema)
And the following tests (I'm sorry it's long, but all my observations are there!):
var myDoc = new MyModel({name: 'My Name'})
describe('My Model Test', function(){
before('we start fresh...', function(done){
MyModel.remove(function(){
done()
})
})
afterEach('and we clean after every test', function(done){
MyModel.remove(function(){
done()
})
})
it('should fail saving duplicate id', function(done){
myDoc.save(function(){
var myDuplicate = new MyModel(myDoc)
//I'll make sure that it's a copy first...
myDuplicate.should.have.property('id', myDoc.id)
myDuplicate.save(function(err){
should.exist(err)
done()
})
})
})
//SO FAR SO GOOD, but now it gets weird
it('should fail saving duplicate name', function(done){
//to make it really fair, lets change the name of myDoc
myDoc.name = 'Another name'
myDoc.save(function(err, doc, affected){
console.log(affected) //First, this outputs 0... weird
var otherDoc = new MyModel({name: 'Another name'})
otherDoc.save(function(err, otherDoc){
should.exist(err) //Nope, no error whatsoever
done()
})
})
})
})
I'm sure there's something wrong with the second call to myDoc#save() but I can't figure out why, I modified the model and mongoose should be able to know I want to save it, and over that, the db is clean so it should insert a new document in the database, not update it. The affected rows return 0, that means that mongoose didn't touch the database, so what is going on? am I using mongoose wrong? if so, how should I test this?
The only way around it is creating a new instance of MyModel in the myDoc var, and then save it, but I feel there's something else in place here... Please help!.