akonwi / backbone.nedb

Use Backbone models with NeDB rather than a traditional database or network layer
MIT License
3 stars 2 forks source link

Example #3

Open karneaud opened 10 years ago

karneaud commented 10 years ago

Can we get some example code for the nodejs noobs?

akonwi commented 10 years ago

I think I deleted the code that I wrote with this when I switched to a chrome app and I don't plan on extending this anymore.

But it works like this:

Backbone = require 'backbone'
Datastore = require 'nedb'
sync = require 'backbone.nedb'
sync(Backbone) # Pass Backbone to sync so it can replace the default Backbone.Sync

# do stuff
window.db = new Datastore() # unfortunately, right now 'db' needs to be a global

me = new Backbone.Model(name: 'akonwi')

me.save()

db.findOne name: 'akonwi', (err, doc) ->
  # doc is just a plain object here without the backbone extras
  console.log(doc.name) # => 'akonwi'

You can look at the tests for more examples. I think that would be very useful

karneaud commented 10 years ago

@akonwi ...THANKS!! I figured this out myself I am using nodejs

Backbone = require('backbone');
require('backbone.nedb')(Backbone); 
Player = Backbone.Model.extend({ idAttribute: "_id", db: new Datastore({filename: path.join(__dirname, '../data/players.db'), autoload:true })});

Note the extending of models to contain the db ...since Backbone is so extensible why not extend the object with the Datastore...

Thus in your backbone_sync.js

I changed the

var attributes;
        console.log("creating model...");
        attributes = model.toJSON();
        return db.insert(attributes, function(err, doc) 

to

var attributes;
        console.log("creating model...");
        attributes = model.toJSON();
        return model.db.insert(attributes, function(err, doc) 

I'm using separate datastore collections for my custom models so it kind of suits me well here...

I was going to branch it and do a pull request but I'm not sure how conventional this was in keeping with you policies....what do you think?

akonwi commented 10 years ago

Awesome! Being able to use different stores for collections was something I wanted to have so go for it.