Wednesday, 31 May 2017

How to handle undefined properties between client and MongoDB

I have a class called Source like the following:

class Source {
    constructor({
        _id = null,
        videos = [],
        articles = [],
        user_id,
        likes,
    } = options) {
        this._id = _id
        this.videos = videos
        this.articles = articles
        this.user_id = user_id
        this.likes = likes
    }

    like() {
        this.likes++
    }

    static map(objects) {
        return objects.map(obj => new Source(obj))
    }

    static get collectionName() {
        return Source.name
    }
}

With an instance of this class it will have undefined attributes for user_id and likes if nothing is specified. MongoDB makes all detected undefined values to null which is not something I desire.

  • What is a clean way of pushing and fetching data with MongoDB while preserving undefined on the client?
  • Should I delete all properties which are undefined before pushing the data?
    • This feels a bit cumbersome and comes with a performance penalty.
  • Should I avoid undefined/null and use default values?
    • This would introduce a problem when excluding fetching a field at which point it looks like it's at a start value. Eg. excluded likes count will be 0 when the MongoDB response is parsed to Source objects.


via E. Sundin

No comments:

Post a Comment