Mongoose or MongoDB for Schema definition?

Viewed 459

Mongoose is used to define a schema. right? Is it is possible to create a schema with mongoDB through mongo Shell ? like

eg: name:String

4 Answers

MongoDB doesn't support schema. It's a schemaless document based DB.

Mongoose is an ODM(Object Document Mapper) that helps to interact with MongoDB via schema, plus it also support validations & hooks.

Basically mongodb is schema less database we cant able to create schema directly in mongodb. Using mongoose we can able to create a schema. Simple CRUD operation using mongoose, for more info ref this link

package.json

{
    "name": "product-api",
    "main": "server.js",
    "dependencies": {
        "express": "~4.0.0",
        "body-parser": "~1.0.1",
        "cors": "2.8.1",
        "mongoose": "~3.6.13"
    }
}

product.js

var mongoose     = require('mongoose');
var Schema       = mongoose.Schema;
var ProductSchema   = new Schema({
    title: String,
    price: Number,
    instock : Boolean,
    photo : String ,
});
module.exports = mongoose.model('Product', ProductSchema);
// module.exports = mongoose.model('Product', ProductSchema,'optiponally pass schema name ');

server.js

var express = require('express');
var bodyParser = require('body-parser');
var cors = require('cors');
var app = express();
var mongoose = require('mongoose');
var product = require('./product');

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var port = process.env.PORT || 8090;
var router = express.Router();

mongoose.connect('mongodb://localhost:27017/products');

// Middle Route 

router.use(function (req, res, next) {
    // do logging 
    // do authentication 
    console.log('Logging of request will be done here');
    next(); // make sure we go to the next routes and don't stop here
});


router.route('/products').post(function (req, res) {
    console.log("in add");
    var p = new product();
    p.title = req.body.title;
    p.price = req.body.price;
    p.instock = req.body.instock;
    p.photo = req.body.photo;
    p.save(function (err) {
        if (err) {
            res.send(err);
        }
        console.log("added");
        res.send({ message: 'Product Created !' })
    })
});

router.route('/products').get(function (req, res) {
    product.find(function (err, products) {
        if (err) {
            res.send(err);
        }
        res.send(products);
    });
});

router.route('/products/:product_id').get(function (req, res) {


    product.findById(req.params.product_id, function (err, prod) {
        if (err)
            res.send(err);
        res.json(prod);
    });
});

router.route('/products/:product_id').put(function (req, res) {

    product.findById(req.params.product_id, function (err, prod) {
        if (err) {
            res.send(err);
        }
        prod.title = req.body.title;
        prod.price = req.body.price;
        prod.instock = req.body.instock;
        prod.photo = req.body.photo;
        prod.save(function (err) {
            if (err)
                res.send(err);

            res.json({ message: 'Product updated!' });
        });

    });
});

router.route('/products/:product_id').delete(function (req, res) {

    product.remove({ _id: req.param.product_id }, function (err, prod) {
        if (err) {
            res.send(err);
        }
        res.json({ message: 'Successfully deleted' });
    })

});


app.use(cors());
app.use('/api', router);
app.listen(port);
console.log('REST API is runnning at ' + port);

Mongoose has its benefits of validation and schema configurations but it has its cons of latency and some problems with high/mid scale applications.

it's always the best thing IMHO, to use the native mongodb package.

regarding schema, you can create your own "schema" as a json file and write ur own validations for mandatory or valid attributes.

it's faster, with no third party packages and more reliable.

Related