moiz-mongo

1.2.51 • Public • Published

moiz-mongo

moiz-mongo is a more easy (Moiz) MongoDB API. It provides a simple and easy to use data access layer based for MongoDb on promises.

Installation

First install node.js and mongodb. Then:

$ npm install moiz-mongo

Overview

Setting up Schema file

First, we need to create a schema that will be used by API to defines Model.

// Schema.js

var userSchema = mongoose.Schema({
	local: {
		username: String,
		password: String
	},
	facebook: {
		id: String,
		token: String,
		email: String,
		name: String
	},
	google: {
		id: String,
		token: String,
		email: String,
		name: String
	},
	token: {
		type: Schema.Types.ObjectId,
		ref: 'Token',
		default: null
	}
});


module.exports = {

	"User" :userSchema ,

	"Car" : 
		{
			schema : {
			   description: { type: String, required: true }
			},
			options : { strict: false,  _id: false,  versionKey: false  }
		},
	"Person" : null	
};

 

The above code defines two model - User, Car, Person.

Note: Your schema definition for model could have following properties

  • schema - defining model
  • options - additional storage rules

If the model definition is assigned "null" value like in our case "Person" model then default schema is applied.

MongoDb Connnection String

var connectionString = 'mongodb://xxx:xxx@xxxx.mongolab.com:53164/xxxx';
    

Using moiz-mongo

var Db = require('moiz-mongo');
var db = new Db(connectionString, './Schema'); 

Find item

Find by Id

Finds item by "_id" field value and returns Promise

db.Person.findById('123');

Find by condition

db.Person.find({name : 'Mike'});

Select specific fields

db.Person.find({name : 'Mike'} ,"name,age");

Find by condition , projection and sort

db.Person.find({name : 'Mike'},"name,age" , {name :1});

Find by no condition , projection, sort and paging

db.Person.find({},"name,age" , {name :1}, {skip : 10 , limit : 10});

Example of using with Express route

router.get('/:id', function (req, res) {

    		var id = req.params.id;
        	db.Person.findById(id)
    				.then(function(result) {
		    			res.json(result);     
		            }).catch(function(err) {
	               		res.status(500).json({error :err});     
		            });
        
    });

Saving item

Save

save() method upserts (insert or update) item based on "_id" field and returns Promise

db.Person.save({name:'John'});

Insert new item

db.Car.insert({name:'GMC II'});

Bulk insert

var list = [
	{name : 'Toyota Hilux'},
	{name : 'Maruti 800'}
];
db.Car.bulkInsert(list);

Update item by Id

db.Car.updateById(1, {name:'Lexus G'});

Update item by condition

db.Car.update({name : 'Lexus X'}, {name:'Lexus G'});

Remove item

Remove by Id

db.User.removeById(123);

Remove by condition

db.User.remove({username : 'test'});

Remove all

db.User.remove();

Aggregation

Count

db.Person.count();

Count by condition

db.Person.count({gender : 'M'});

Group by (aggregation)

db.Person.aggregrate({
			 $group: {
                _id: '$gender',   
                count: {$sum: 1}
            }
		})

In the above code we get count by gender field.

Initialize with empty Schema and update later

 var db = new Db(connectionString, {});
 db.updateModelSchema('Person', newMongooseSchema, 'People')
 db.updateModelSchema('Car', carSchema); // without collection name, so it will pluralize
 db.Person.save({name:'Moiz'});
 db.Car.save({name:'RE'});

updateModelSchema()

In the above example we create "db" instance with empty schema. Then we update Model schema using updateModelSchema() function.

Here argument

  • 'Person' - name of the property in "db" object
  • newMongooseSchema - mongoose schema definition
  • 'People' - name of collection in mongodb

updateModelSchemaIfDoesntExist()

This method will update model schema only if the property doesn't exist in db instance.

db.updateModelSchemaIfDoesntExist('Car', carSchema);

In above example since the model schema will be not be updated if there is already a propery name "Car" in "db"

License

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

Package Sidebar

Install

npm i moiz-mongo

Weekly Downloads

0

Version

1.2.51

License

BSD-2-Clause

Last publish

Collaborators

  • moizoliya