Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose create test data and populate without a database connection

I am writing a unit test that uses a mongoose model which has nested object. I want to populate the main model and the referenced model without calling 'populate' and fetching 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 an id and not to the engine object. Is there a way to get this working?

like image 701
marto Avatar asked Sep 29 '22 13:09

marto


1 Answers

calling setValue will retain the hydrated document:

car1.setValue('engine', engine1)
like image 96
Andrew Homeyer Avatar answered Oct 02 '22 16:10

Andrew Homeyer