vadimdemedes / mongorito

🍹 MongoDB ODM for Node.js apps based on Redux
1.38k stars 90 forks source link

Bug with empty fields after using 'Model.embeds()' #191

Closed Zizaco closed 7 years ago

Zizaco commented 7 years ago

@vadimdemedes

Model.embeds is causing an unexpected behavior. Even when the field value is undefined it still returns an object. This is a problem, I guess

It's very easy to reproduce:

const Model = require('mongorito').Model

class Post extends Model {}
class Comment extends Model {}
class Author extends Model {}

Post.embeds('author', Author);
Post.embeds('comments', Comment);

let post = new Post() // empty
typeof post.get('author') // "object" <- This is bizarre
post.get('author').constructor // [Function: Author] <-
typeof post.get('comments') // "object" <-
post.get('comments').constructor // [Function: Comment] :dizzy_face: 

With this behavior, if a Post don't have any comments or no author it's very easy to fall into a problem like the one bellow:

// [...]
if (post.get('author') === undefined) { // will never be true :dizzy_face: 
  // present as "anonymous"
} else {
  // display author
}

Shouldn't we change this behavior to return undefined if the field is actually undefined?

Btw, thank you for this awesome package