Search code examples
firebaseember.jsfirebase-realtime-databaseember-data

How to push or update data with emberfire?


Edit: See solution at the end

My guess was to put the model (in my case 'user') inside => type, but then it'll say "Assertion failed, you need to pass a model ..."

I do have a user.js in app/models

here's an excerpt from the router (after login function)

self.store.push({
                data: {
                    id: data.currentUser.uid,
                    type: 'user',
                    attributes: {
                        displayName: data.currentUser.displayName,
                        email: data.currentUser.email,
                        photoURL: data.currentUser.photoURL,
                        firebaseUID: data.currentUser.uid,
                        rank: "scorer",
                        status: "active",
                        loginCount: 0,
                        provider: provider,
                        timestamp: new Date().getTime()
                    }
                }
            });

and here's my model (user.js in app/models)

import DS from 'ember-data';

export default DS.Model.extend({
  displayName: DS.attr('string'),
  email: DS.attr('string'),
  photoURL: DS.attr('string'),
  firebaseUID: DS.attr('string'),
  rank: DS.attr('string'),
  status: DS.attr('string'),
  loginCount: DS.attr('string'),
  provider: DS.attr('string'),
  timestamp: DS.attr('number')
});

Please help :( thanks everyone in advance!

Edit => Solution that worked: If you do a createRecord and match the "id:" attribute, it will update the record with the same id (will work if you specified your own id). However, I'm not sure yet how to update a record if you let the system generate an ID for you. I assume that you would have to extract the ID first. But I haven't tested that idea yet. If someone would be so kind to test it, that'll be awesome.


Solution

  • Instead of pushing the raw data, create a model and run its save method.

    var user = this.store.createRecord('user', {
        displayName: data.currentUser.displayName,
        // set more properties here
    })
    user.save()
    

    This way, Emberfire and Ember Data can do their thing and ensure the data is formatted correctly. Also see