Skip to content

Instantly share code, notes, and snippets.

@AydinSakar
Forked from toddself/mongosync.js
Created August 3, 2013 16:54
Show Gist options
  • Save AydinSakar/6147108 to your computer and use it in GitHub Desktop.
Save AydinSakar/6147108 to your computer and use it in GitHub Desktop.
// backbone.sync adaptor that uses mongojs to store models
// returns a q.defer().promise
'use strict';
var mongojs = require('mongojs');
var q = require('q');
module.exports = function (method, model, options) {
var app = require('../app');
var d = q.defer();
var db = mongojs(app.get('db_server'));
var collection = db.collection(app.get('db_collection'));
var db_callback = function (err, response) {
if (err) {
d.reject(err);
}
if (response === 1) {
d.resolve(model.toJSON());
} else {
d.resolve(response[0]);
}
};
switch (method) {
case 'create':
collection.insert(model.toJSON(), {safe: true}, db_callback);
break;
case 'update':
case 'patch':
collection.save(model.toJSON(), db_callback);
break;
case 'delete':
d.reject('Unimplemented');
break;
case 'read':
var _id = model.get('_id');
var query_params = {};
if (_id) {
query_params._id = mongojs.ObjectId(_id);
} else {
d.reject(new Error('You must provide an _id to lookup'));
}
collection.find(query_params, db_callback);
break;
default:
d.reject(new Error('Unimplemented'));
break;
}
return d.promise;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment