Adding New Ember.js Objects/Records when DB Provides ID

陌路散爱 提交于 2019-12-21 05:40:58

问题


I'm experimenting with Ember.js, Node.js and MongoDB. I've based my noodling on the excellent video on the Ember site and Creating a REST API using Node.js, Express, and MongoDB. I've hit a roadblock on the Ember.js side trying to get my create record functionality working.

Currently, when a user creates a record in my sample application, two will show up in the listing. This is happening because when I save my record to the server, a new ID is created for that record by MongoDB. When the response is returned (containing the object with the new ID), the record is duplicated until I refresh the page. One has the new Mongo-supplied ID and the other has a NULL.

Here is where I create the new object:

App.NewwineRoute = Ember.Route.extend({
   model: function() {
          return App.Wine.createRecord();
   }
});

Here is where I store the record to MongoDB:

App.NewwineController = Ember.ObjectController.extend({
    doneEditing: function() {
        this.get('store').commit();
        this.transitionToRoute('wines');
    }
});

I'm curious what the best way to handle this is when using ember-data? I've tried all kinds of tricks and worn my connection out searching for examples.

The closest I've been is a nasty hack of setting an id of -1 to the new object/record and then attempting to remove it after the commit. Sadly, the object/record wouldn't really be removed, just show up blank in my list. Plus, I couldn't create any objects/records with an id of -1 from that point on (because one already exists). Seems like a dead-end.

Thanks in advance.

>'.'<

SOLUTION:

I was able to glean the solution to the problem from the following AMAZING examples:

Ember.js CRUD REST

Node.js REST Server for Ember

For others that have had the ID problem, the App.Adapter in the above example handles the mapping from "_id" to "id".

App.Adapter = DS.RESTAdapter.extend({
  serializer: DS.RESTSerializer.extend({
    primaryKey: function (type){
      return '_id';
    }
  })
});

Inside of the example's Node.js service, the DB calls map "id" to "_id":

collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item) {

Thanks again to ddewaele for sending over the example, it was a great tutorial for linking these technologies together.

来源:https://stackoverflow.com/questions/16392258/adding-new-ember-js-objects-records-when-db-provides-id

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!