New Case Study:See how Anthropic automated 95% of dependency reviews with Socket.Learn More
Socket
Sign inDemoInstall
Socket

mong

Package Overview
Dependencies
Maintainers
1
Versions
23
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

mong - npm Package Compare versions

Comparing version 1.1.0 to 2.0.0

170

lib/connection.js

@@ -1,108 +0,118 @@

'use strict';
'use strict'
var MongoClient = require('mongodb').MongoClient;
var EventEmitter = require('events').EventEmitter;
var inherits = require('util').inherits;
var ObjectId = require('mongodb').ObjectID;
var MongoClient = require('mongodb').MongoClient
var EventEmitter = require('events').EventEmitter
var inherits = require('util').inherits
var ObjectId = require('mongodb').ObjectID
var Document = require('./model');
var promisify = require('./promisify');
var Document = require('./model')
var $private = require('./private').create();
var DB = Symbol('dbPromise')
var PROMISE_COLLECTION = Symbol('dbCollection')
module.exports = Connection;
function pluralize (constructorName) {
return constructorName.toLowerCase() + 's'
}
inherits(Connection, EventEmitter);
module.exports = Connection
function Connection(uri) {
EventEmitter.call(this);
$private(this).queued = [];
if (uri) {
connect.call(this, uri);
inherits(Connection, EventEmitter)
function Connection (uri) {
EventEmitter.call(this)
var conn = this
inherits(ConnectedDocument, Document)
function ConnectedDocument (o) {
Document.call(this, o)
}
}
Connection.prototype.ObjectId = ObjectId;
Connection.prototype.connect = promisify(connect);
function connect(uri, done) {
var options = {
db: {
'native_parser': true
}
};
// Mixin static methods:
Object.keys(Document)
.forEach(function (staticMethodName) {
ConnectedDocument[staticMethodName] = Document[staticMethodName]
})
var conn = this;
var dbPromise = new Promise(function (resolve, reject) {
conn.once('connect', function () {
resolve(conn[DB])
})
})
ConnectedDocument.getCollection = function () {
var p = ConnectedDocument[PROMISE_COLLECTION]
if (p) return p
var self = this
p = dbPromise
.then(function (db) {
var collectionName = self.collection
if (typeof collectionName === 'function') collectionName = collectionName()
if (typeof collectionName !== 'string') collectionName = pluralize(self.name)
return db.collection(collectionName)
})
MongoClient.connect(uri, options, function (err, db) {
if (err) {
if (done) {
return done(err);
}
return conn.emit('error', err);
}
ConnectedDocument[PROMISE_COLLECTION] = p
var queued = $private(conn).queued;
return p
}
$private(conn).db = db;
$private(conn).queued = null;
this.Document = ConnectedDocument
// Execute all of the queued functions:
queued.forEach(function (fn) { fn(db); });
if (uri) {
connect.call(this, uri)
}
}
if (done) done(null, conn);
Connection.prototype.model = function (collectionName) {
var ConnectedDocument = this.Document
conn.emit('connect', conn);
});
var ctor = function (o) {
ConnectedDocument.call(this, o)
}
inherits(ctor, ConnectedDocument)
return this;
// Mixin static methods:
Object.keys(ConnectedDocument)
.forEach(function (staticMethodName) {
ctor[staticMethodName] = ConnectedDocument[staticMethodName]
})
ctor.collection = function () {
return collectionName
}
return ctor
}
Connection.prototype.queue = function (fn) {
var queue = $private(this).queued;
if (!queue) return fn(this);
queue.push(fn);
};
Connection.prototype.ObjectId = ObjectId
Connection.prototype.disconnect = promisify(function (done) {
var active = $private(this).db;
delete $private(this).db;
Connection.prototype.connect = connect
if (active) {
return active.close(done);
function connect (uri) {
this.connect = function connectionAlreadyOpen () {
throw new Error('Connection already open.')
}
if (done) done();
});
/**
* Create a new model linked to a mongodb collection.
* @param {String} collectionName Name as in database.
* @return {Constructor} document constructor
*/
Connection.prototype.model = function (collectionName) {
function CollectionDocument(o) {
Document.call(this, o);
var options = {
db: {
'native_parser': true
}
}
// Inherit static methods: (.find() etc)
CollectionDocument.__proto__ = Document;
var conn = this
var self = this;
var p = MongoClient.connect(uri, options)
CollectionDocument.setConnection(self);
CollectionDocument.setCollectionProvider(function () {
return $private(self).db.collection(collectionName);
});
p.then(
function (db) {
conn[DB] = db
conn.emit('connect')
},
function (err) { conn.emit('error', err) }
)
return p
}
CollectionDocument.prototype = Object.create(Document.prototype, {
constructor: {
value : CollectionDocument,
enumerable : false,
writable : true,
configurable : true
}
});
return CollectionDocument;
};
Connection.prototype.disconnect = function () {
return this[DB].close()
}

@@ -1,10 +0,10 @@

'use strict';
'use strict'
exports.ObjectId = require('mongodb').ObjectID;
exports.Connection = require('./connection');
exports.ObjectId = require('mongodb').ObjectID
exports.Connection = require('./connection')
exports.createConnection = function (uri) {
return new exports.Connection(uri);
};
return new exports.Connection(uri)
}
exports.create = exports.createConnection;
exports.create = exports.createConnection

@@ -1,25 +0,28 @@

'use strict';
'use strict'
module.exports = Document;
module.exports = Document
var ObjectId = require('mongodb').ObjectID;
var QueryStream = require('./stream');
var $private = require('./private').create();
var p = require('./promisify');
var mapStream = require('map-stream')
var ObjectId = require('mongodb').ObjectID
var PROTO = '__proto__'
module.exports = Document
function Document (o) {
o = o || {};
o = o || {}
// Cast _id to ObjectId
if (typeof o._id === 'string') {
this._id = new ObjectId(o._id);
this._id = new ObjectId(o._id)
} else if (typeof o._id === 'object') {
this._id = o._id;
this._id = o._id
}
this._id = this._id || new ObjectId();
this._id = this._id || new ObjectId()
for(var i in o) {
for (var i in o) {
if (i !== '_id' && Object.hasOwnProperty.call(o, i)) {
this[i] = o[i];
this[i] = o[i]
}

@@ -34,9 +37,18 @@ }

*/
function getCollection(constructor) {
var conInternal = $private(constructor);
if (!conInternal.collection) {
conInternal.collection = conInternal.collectionProvider(constructor);
delete conInternal.collectionProvider;
function get (constructor) {
return constructor.getCollection()
}
function convert (proto) {
return function (result) {
if (!result) return result
if (Array.isArray[result]) {
result.forEach(function (doc) {
doc[PROTO] = proto
})
return result
}
result[PROTO] = proto
return result
}
return conInternal.collection;
}

@@ -46,173 +58,90 @@

/**
* Set Collection provider function
* @param {Constructor -> MongoDB.Collection} provider funciton which gets called once the first time this model is used.
*/
Document.setCollectionProvider = function (provider) {
$private(this).collectionProvider = provider;
};
Document.findById = function (_id) {
if (typeof _id === 'string') _id = new ObjectId(_id)
return this.findOne.apply(this, arguments)
}
/**
* Set parent connection
* @param {Connection} connection
*/
Document.setConnection = function (connection) {
$private(this).connection = connection;
};
function mapped (name) {
return function () {
var args = arguments
Document.find = p.stream(function (query, fields, options) {
var collection = getCollection(this);
var callback = arguments[arguments.length - 1];
var l = arguments.length;
if (typeof callback === 'function') {
l--;
} else {
callback = null;
return get(this)
.then(function (c) {
return c[name].apply(c, args)
})
.then(convert(this.prototype))
}
switch (l) {
case 0:
query = {};
case 1:
fields = {};
case 2:
options = {};
}
var cursor = collection.find.call(collection, query, fields, options);
}
if (callback) {
var proto = this.prototype;
cursor.toArray(function (err, results) {
if (err) return callback(err);
results.forEach(function (doc) {
doc.__proto__ = proto;
});
callback(null, results);
});
return;
function mappedRawResult (name) {
return function () {
var args = arguments
return get(this)
.then(function (c) {
return c[name].apply(c, args)
})
.then(function (k) {
return k.result
})
}
}
return new QueryStream(cursor, this.prototype);
});
function mappedStream (name) {
return function () {
var prototype = this.prototype
var output = mapStream(function (data, callback) {
data[PROTO] = prototype
callback(null, data)
})
var args = arguments
Document.findOne = p(function () {
var prototype = this.prototype;
var cb = arguments[arguments.length - 1];
arguments[arguments.length - 1] = function (err, doc) {
if (doc) doc.__proto__ = prototype;
cb(err, doc);
};
var collection = getCollection(this);
return collection.findOne.apply(collection, arguments);
});
Document.findById = p(function (_id, callback) {
if (typeof _id === 'string') _id = new ObjectId(_id);
return this.findOne({_id: _id}, callback);
});
Document.findAndModify = p(function () {
var collection = getCollection(this);
return collection.findAndModify.apply(collection, arguments);
});
/**
* MongoDB aggregation pipeline
* http://docs.mongodb.org/manual/reference/command/aggregate/#dbcmd.aggregate
*
* @param [Object] pipeline
* @param {Object} options (Optinal)
* @param {Function} callback Optional. Leave blank for streaming mode.
* @return {Readable} stream which emits results.
*/
Document.aggregate = p.stream(function (pipeline, options) {
var _callback;
var l = arguments.length;
if (typeof arguments[arguments.length - 1] === 'function') {
_callback = arguments[arguments.length - 1];
l--;
}
if (l === 1) {
options = {};
}
var collection = getCollection(this);
if (!options.cursor) {
options.cursor = {};
}
var cursor = collection.aggregate(pipeline, options);
if (_callback) {
var b = [];
cursor.on('data', function (data) {
b.push(data);
get(this)
.then(function (c) {
var input = c[name].apply(c, args)
input.pipe(output)
})
.on('end', function () {
_callback(null, b);
});
return;
.then(null, function (err) {
output.emit('error', err)
})
return output
}
return cursor;
});
}
/**
* Create an index.
* This is the only method which can be used before the connection is open.
* @param {Object} fieldOrSpec
* @param {Object} options
* @param {Function} done callback
*/
Document.ensureIndex = p(function (fieldOrSpec, options, done) {
var self = this;
$private(this).connection.queue(function () {
var collection = getCollection(self);
collection.ensureIndex(fieldOrSpec, options, function (err) {
if (done) return done(err);
// Default callback:
if (err) throw err;
});
});
return this;
});
;['find', 'findOne', 'findAndModify']
.forEach(function (name) {
Document[name] = mapped(name)
})
Document.update = p(function () {
var collection = getCollection(this);
return collection.update.apply(collection, arguments);
});
;['update', 'remove', 'aggregate', 'ensureIndex']
.forEach(function (name) {
Document[name] = mappedRawResult(name)
})
Document.remove = p(function () {
var collection = getCollection(this);
return collection.remove.apply(collection, arguments);
});
Document.stream = mappedStream('find')
Document.aggregateStream = mappedStream('aggregate')
// ===== Instance Methods =====
Document.prototype.save = function () {
var doc = this
return get(this)
.then(function (c) {
return c.save(doc)
})
.then(function () {
return doc
})
}
Document.prototype.save = p(function (done) {
done = done || function (err) {
if (err) throw err;
};
var collection = getCollection(this.constructor);
var self = this;
collection.save(this, function (err) {
if (err) return done(err);
done(null, self);
});
});
Document.prototype.update = function (changes, options) {
var args = [{_id: this._id}].concat(Array.prototype.slice.call(arguments))
return this.constructor.update.apply(this.constructor, args)
}
Document.prototype.update = p(function () {
var collection = getCollection(this.constructor);
var args = [{_id: this._id}].concat(Array.prototype.slice.call(arguments));
return collection.update.apply(collection, args);
});
Document.prototype.remove = function (options) {
var args = [{_id: this._id}].concat(Array.prototype.slice.call(arguments))
return this.constructor.remove.apply(this.constructor, args)
}
Document.prototype.remove = p(function () {
var collection = getCollection(this.constructor);
var args = [{_id: this._id}].concat(Array.prototype.slice.call(arguments));
return collection.remove.apply(collection, args);
});
/**

@@ -225,6 +154,6 @@ * Update command parametrized by ObjectId(this._id).

*/
Document.prototype.updateIf = p(function (query) {
query = Object.create(query);
query._id = this._id;
return Document.update.apply(this.constructor, arguments);
});
Document.prototype.updateIf = function (query, changes) {
query = Object.create(query)
query._id = this._id
return this.constructor.update.apply(this.constructor, arguments)
}
{
"name": "mong",
"version": "1.1.0",
"version": "2.0.0",
"description": "Lightweight models for mongodb objects",
"main": "lib/index",
"scripts": {
"lint": "eslint --ignore-path .gitignore .",
"test": "mocha --recursive test/ && ([[ -z $TRAVIS_JOB_ID ]] || npm run travis)",
"lint": "standard",
"test": "mocha --bail --recursive test/",
"coverage": "mkdir -p coverage && mocha --recursive -r blanket -R html-cov --recursive test/ > coverage/index.html",

@@ -46,3 +46,4 @@ "travis": "mocha -r blanket -R mocha-lcov-reporter --recursive test/ | coveralls"

"es6-promise": "^2.3.0",
"mongodb": "^2.0.39"
"map-stream": "0.0.6",
"mongodb": "^2.0.46"
},

@@ -55,8 +56,8 @@ "directories": {

"coveralls": "^2.11.3",
"eslint": "^0.24.1",
"mocha": "^2.2.5",
"mocha-lcov-reporter": "0.0.2",
"should": "^7.0.2",
"sinon": "~1.7.3"
"sinon": "~1.7.3",
"standard": "^5.3.1"
}
}

@@ -1,23 +0,24 @@

'use strict';
'use strict'
/* global describe it */
var lib = require('../../index');
var should = require('should');
var lib = require('../../')
var should = require('should')
describe('#connect', function () {
it('should connect to a mongodb server', function (done) {
lib.create().connect('mongodb://localhost/mong-test', done);
});
it('should error if the server doesn\'t exist', function (done) {
lib.create().connect('mongodb://localhost:45603', function (err) {
should.exist(err);
done();
});
});
it('should connect to a mongodb server', function () {
return lib.create().connect('mongodb://localhost/mong-test')
})
it('should error if the server doesn\'t exist', function () {
return lib.create().connect('mongodb://localhost:45603')
.then(null, function (err) {
should.exist(err)
})
})
it('should emit an error if the server doesn\'t exist', function (done) {
lib.create('mongodb://localhost:45603')
.on('error', function (err) {
should.exist(err);
done();
});
});
});
should.exist(err)
done()
})
})
})

@@ -1,24 +0,24 @@

'use strict';
'use strict'
/* global describe it */
var lib = require('../../index');
var lib = require('../../')
describe('Model()', function () {
it('should keep all of the properties', function () {
var db = lib.create();
var Model = db.model('animals');
Model.ensureIndex({name: 1});
var object = {x:3};
Model.call(object, {y: 12, z: 300, _id: '55338635d671fa19fe5855c6'});
object.x.should.equal(3);
object.y.should.equal(12);
object.z.should.equal(300);
object._id.should.not.be.an.instanceOf(String);
object._id.should.be.an.instanceOf(lib.ObjectId);
object._id.equals('55338635d671fa19fe5855c6').should.equal(true);
var db = lib.create()
var Model = db.model('animals')
Model.ensureIndex({name: 1})
var object = {x: 3}
Model.call(object, {y: 12, z: 300, _id: '55338635d671fa19fe5855c6'})
object.x.should.equal(3)
object.y.should.equal(12)
object.z.should.equal(300)
object._id.should.not.be.an.instanceOf(String)
object._id.should.be.an.instanceOf(lib.ObjectId)
object._id.equals('55338635d671fa19fe5855c6').should.equal(true)
var o2 = {};
Model.call(o2, {_id: new lib.ObjectId('55338635d671fa19fe5855c6')});
o2._id.equals('55338635d671fa19fe5855c6').should.equal(true);
});
});
var o2 = {}
Model.call(o2, {_id: new lib.ObjectId('55338635d671fa19fe5855c6')})
o2._id.equals('55338635d671fa19fe5855c6').should.equal(true)
})
})

@@ -1,18 +0,19 @@

'use strict';
'use strict'
/* global before after describe it */
var lib = require('../../index');
var should = require('should');
var sinon = require('sinon');
var MongoClient = require('mongodb').MongoClient;
var ObjectId = require('mongodb').ObjectID;
var lib = require('../../')
var should = require('should')
var sinon = require('sinon')
var MongoClient = require('mongodb').MongoClient
var ObjectId = require('mongodb').ObjectID
var db;
var collection;
var db
var collection
var User;
var User
var random = Math.random();
var _id = new ObjectId('52d3bca3e25e47fc2d860000');
var _id2 = new ObjectId('52d3bca3e25e47fc2d860300');
var uri = 'mongodb://localhost/mong-test2';
var random = Math.random()
var _id = new ObjectId('52d3bca3e25e47fc2d860000')
var _id2 = new ObjectId('52d3bca3e25e47fc2d860300')
var uri = 'mongodb://localhost/mong-test2'

@@ -22,104 +23,98 @@ describe('Model', function () {

MongoClient.connect(uri, function (err, _db) {
if (err) return done(err);
collection = _db.collection('users');
should.exist(collection);
if (err) return done(err)
collection = _db.collection('users')
should.exist(collection)
collection.insert({_id: _id, random: random}, function () {
collection.insert({_id: _id2, random: Math.random()}, function () {
_db.close(done);
});
});
});
});
_db.close(done)
})
})
})
})
before(function (done) {
db = lib.create(uri);
User = db.model('users');
db = lib.create(uri)
User = db.model('users')
User.ensureIndex({name: 1});
User.ensureIndex({name: 1})
db
.on('error', done)
.on('connect', function () {
done();
});
});
done()
})
})
after(function (done) {
db.disconnect(done);
db.disconnect();
});
after(function () {
return db.disconnect()
})
describe('.find', function () {
it('should find the objects already in the collection', function (done) {
var expectation = sinon.mock();
expectation.once();
var expectation = sinon.mock()
expectation.once()
User.find({_id: _id})
User.stream({_id: _id})
.on('data', expectation)
.on('end', function () {
if (!expectation.firstCall.args[0]._id.equals(_id)) throw new Error('Wrong _id');
expectation.verify();
done();
});
});
if (!expectation.firstCall.args[0]._id.equals(_id)) throw new Error('Wrong _id')
expectation.verify()
done()
})
})
it('should support callbacks', function (done) {
User.find(done);
});
it('should support promises', function () {
return User.find()
.then();
});
.then()
})
it('should support providing callbacks', function (done) {
it('should support providing promises', function () {
User.find({}, {}, {sort: {_id: -1}})
.then(function (docs) {
docs.should.be.an.instanceOf(Array)
})
})
})
User.find({}, {}, {sort: {_id: -1}}, function (err, docs) {
docs.should.be.an.instanceOf(Array);
done(err);
});
});
});
describe('.findOne', function () {
it('should support callbacks', function (done) {
User.findOne({_id: _id}, done);
});
});
it('should support promises', function () {
return User.findOne({_id: _id})
})
})
describe('.findById', function () {
it('should support callbacks', function (done) {
User.findById(_id, done);
});
});
it('should support promises', function () {
return User.findById(_id)
})
})
describe('.update', function () {
it('should support callbacks', function (done) {
User.update({_id: _id}, {$set: {list: [1, 2, 3]}}, done);
});
});
it('should support promises', function () {
return User.update({_id: _id}, {$set: {list: [1, 2, 3]}})
})
})
describe('.remove', function () {
it('should support callbacks', function (done) {
User.remove({none: 'match'}, done);
});
});
it('should support promises', function () {
return User.remove({none: 'match'})
})
})
describe('.findAndModify', function () {
it('should support callbacks', function (done) {
User.findAndModify({xyz: 123}, {}, {$set: {z: -4}}, done);
});
});
it('should support callbacks', function () {
return User.findAndModify({xyz: 123}, {}, {$set: {z: -4}})
})
})
describe('.aggregate', function () {
it('should support callbacks', function (done) {
User.aggregate([{$group: {_id: null}}], done);
});
it('should support callbacks', function () {
return User.aggregate([{$group: {_id: null}}])
})
it('should support streams', function (done) {
var expectation = sinon.mock();
expectation.once();
User.aggregate([{$group: {_id: null}}])
var expectation = sinon.mock()
expectation.once()
User.aggregateStream([{$group: {_id: null}}])
.on('data', expectation)
.on('end', done);
});
});
});
.on('end', done)
})
})
})

@@ -1,14 +0,15 @@

'use strict';
'use strict'
/* global describe it */
var lib = require('../../index');
var should = require('should');
var lib = require('../../')
var should = require('should')
describe('Model.init', function () {
it('should copy all of the static methods', function () {
var User = lib.create().model('users');
should.exist(User.find);
should.exist(User.findOne);
should.exist(User.update);
should.exist(User.findAndModify);
});
});
var User = lib.create().model('users')
should.exist(User.find)
should.exist(User.findOne)
should.exist(User.update)
should.exist(User.findAndModify)
})
})

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc