scottwrobinson / camo

A class-based ES6 ODM for Mongo-like databases.
556 stars 80 forks source link

Issue saving with required reference document #101

Open ss44 opened 7 years ago

ss44 commented 7 years ago

Came across an issue when saving a document without first saving the reference document triggering a validation error, if the reference document is not created first.

I realise this can be worked around by first creating the reference doc, saving it and then adding it to user, but seems like this case should also work.

Error:

failed updating user ::  ValidationError: Key users.pet is required, but got undefined
    at /dev/node_modules/camo/lib/base-document.js:201:23
    at Array.forEach (native)
    at User.validate (/dev/node_modules/camo/lib/base-document.js:160:30)
    at /dev/node_modules/camo/lib/document.js:68:18

Error can be replicated with:

const connect = require('camo').connect
const Document = require('camo').Document

class User extends Document {
  constructor () {
    super()
    this.name = String
    this.pet = {
      type: Pet,
      required: true
    }
  }
}

class Pet extends Document {
  constructor () {
    super()
    this.type = String
    this.name = String
  }
}

connect('nedb://testdb')
  .then(() => {
    let pet = Pet.create()
    pet.name = 'Dog'
    pet.type = 'Rover'

    let user = User.create()
    user.name = 'Sam Smith'
    user.pet = pet

    return user.save()
  })
  .catch((err) => {
    console.log('error saving :: ', err)
  })
  .then(() => {
    console.log('User saved!')

    // Load the user
    return User.findOne()
  })
  .then((user) => {
    console.log('found user -- ', user.name)
    user.name = 'Changed users name'

    return user.save()
  })
  .then(() => {
    console.log('sucessfully updated user!')
  })
  .catch((err) => {
    console.log('failed updating user :: ', err)
  })