npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

moiz-mongo

v1.2.51

Published

Easy to use Data Access layer based on promises for Mongo

Downloads

46

Readme

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:[email protected]: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.