Skip to content

Instantly share code, notes, and snippets.

@abhishekr700
Last active February 10, 2018 21:29
Show Gist options
  • Save abhishekr700/e51bff5fcf708b078995e043f6b478a8 to your computer and use it in GitHub Desktop.
Save abhishekr700/e51bff5fcf708b078995e043f6b478a8 to your computer and use it in GitHub Desktop.

Node.js use MongoDB using Mongoose module

( Each model in separate file )

mongo.js

This file holds connection to DB & also creates schema by importing them from other files.
//Import the mongoose module
const mongoose = require("mongoose");

//Import DB Models
const mymodel = require("./mymodel.js");

//Connect to DB , useMongoClient: true => Connect using new connection logic (old one deprecated)
//eg. URI : mongodb://localhost:port/dbname
mongoose.connect(" mongodb://localhost:port/dbname " , {
  useMongoClient: true
}).then(()=>{
    console.log("Successful connection to MongoDB");
})
.catch((err)=>{
    console.log("Mongoose connection error due to: ",err);
});

/*
By default no mongoose promises have a .catch() (backwards compatibility reasons) (https://github.com/Automattic/mongoose/issues/3509)
So, we use global Promises
*/
mongoose.Promise = global.Promise;

//Expose the models for using elsewhere
module.exports = {
  mymodel
}


mymodel.js

This file holds the schema for mymodel
const mongoose = require("mongoose");

const mymodelSchema = mongoose.Schema({
    name: String,
    category: Number,
    userID: {
        type: mongoose.Schema.Types.ObjectId,
        ref: "users"
    }
})

module.exports = mongoose.model("mymodelname" , mymodelSchema);

Mongoose Querying Basics for newbies

Products = Table variable exported from mongoose.js

[projection] Specifies what fields to return.

A projection cannot contain both include and exclude specifications, except for the exclusion of the _id field.
The projection parameter takes a document of the following form:
        { field1: <value>, field2: <value> ... }
The <value> can be any of the following:
- 1 or true to include the field in the return documents.
- 0 or false to exclude the field.

**The find() method always returns the _id field unless you specify _id: 0 to suppress the field.

Projection Docs

Products.findById(req.params.id,{
        _id: 0,   //exclude
        name: 1,  //include
        desc: 1   //include
    })
        .then( (item)=>{
            console.log("Item:",item);
            res.send(item);
        })
        .catch((err)=>{
            console.log(err);
            res.send(err);
        })

findById(id, [projection], [options], [callback])

Returns a "Query" which is a Promise "item" gets the data or if not found then it gets "null". Error handles using .catch()

Products.findById(req.params.id)
        .then( (item)=>{
            res.send(item);
        })
        .catch((err)=>{
            console.log(err);
        })
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment