joegoldbeck / mongoose-encryption

Simple encryption and authentication plugin for Mongoose
MIT License
215 stars 51 forks source link

Nested Fields create an empty object if the parent field doesn't exist #66

Open grrseguin opened 7 years ago

grrseguin commented 7 years ago

Hello,

With the config above a new document will always have field1: {} if field1 is not provided.

const subUserSchema = new Schema({
  field2: {
    type: String,
  },
});

const userSchema = new Schema({
  field1: {
    type: subUserSchema,
  },
});

userSchema.plugin(encrypt, { encryptionKey: encKey, signingKey: sigKey, encryptedFields: ["field1.field2"], });

IMHO, field1 should not be created, WDYT?

Version "mongoose-encryption": "1.5.0",

joegoldbeck commented 7 years ago

I definitely agree. I wonder if this relates to https://github.com/joegoldbeck/mongoose-encryption/issues/65

I don't have time to dig into this in the near-term, but would be happy to review any PRs accompanied with tests!

grrseguin commented 7 years ago

Why not for the PR.

But before, by reading the Encrypt Specific Fields of Sub Docs section in the README.md file, i resolved the problem.

const subUserSchema = new Schema({
  field2: {
    type: String,
  },
});

subUserSchema.plugin(encrypt, { encryptionKey: encKey, signingKey: sigKey, encryptedFields: ["field2"], });

const userSchema = new Schema({
  field1: {
    type: subUserSchema,
  },
});
grrseguin commented 7 years ago

Maybe Nested Fields section should be replaced by Encrypt Specific Fields of Sub Docs section in the README file.

I don't see any differences between nested fields & sub docs, WDYT ?

joegoldbeck commented 7 years ago

Ah that makes sense. Apparently there is a difference at the Mongoose level (though Mongo itself of course doesn't really care), hence the support for both.