0

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!.

fixmycode
  • 8,220
  • 2
  • 28
  • 43

1 Answers1

1

You are executing MyModel.remove() after every test. Since you're defining the myDoc variable outside of the test blocks it's scope is global to the file. By saving the document in the first test the document will get added to the collection, then deleted after the test runs.

So, when your second test executes mongoose will think the document still exists in the database and tries to perform an update on the existing _id that's stored in the myDoc object. Since the document no longer exists in the database it'll return 0 because no documents were updated. The second save will also return 0, and not an error, for the same reason.

Try creating a new document within the second test, instead of defining it globally. That should do the trick.

Brian Shamblen
  • 4,653
  • 1
  • 23
  • 37