Mongoose creates test data and populates without connecting to a database

I am writing a unit test that uses a mongoose model with a nested object. I want to populate the main model and the reference model without causing it to “populate” and retrieve anything from the database. Here is an example in coffeescript

CarSchema = new mongoose.Schema
  name:
    type: String
    required: true
  engine:
    type: ObjectId
    ref: 'Engine'
    required: true

Car = mongoose.model('Car', CarSchema)

EngineSchema = new mongoose.Schema
  name:
    type:String
    required: true

Engine = mongoose.model('Engine', EngineSchema)

engine1 = new Engine({name: 'test'})
car1 = new Car({engine: engine1, name: 'car'})

assert.equal (car1.engine.name, 'test') #this fails

What happens is that car1.engine is set to id and not to the engine object. Is there any way to make this work?

+4
source share
1 answer

The call will setValuesave the dampened document:

car1.setValue('engine', engine1)
+3
source

All Articles