Save a Document Into MongoDB Mongoose (Node.JS)

Code Snippets 4 U
var express = require('express')
var route1 = express.Router()
var db = require('mongoose')

// create options for connect method. useNewUrlParser argument is needed because of deprecation of old url parser
var options = {
    keepAlive: 300000,
    connectTimeoutMS: 30000,
    useNewUrlParser: true
};

db.connect('mongodb://username:[email protected]:23372/dbName', options)

// get the connection object. Which emits events error, open etc.
var conn = db.connection;

// check for error event
conn.on('error', console.error.bind(console, 'connection error:'));

// open event occurs when connection is made successfully

conn.on('open', function() {
    // creat schema

    var documentSchema = db.Schema({
        name: String,
        date: {
            type: Date,
            default: Date.now
        },
        timestamp: String
    })

    //create model with first argument as the name of collection in which the document will be stored and second as schema object created

    var documentModel = db.model("document", documentSchema)

    // create a object that will store out data

    var newDocument = new documentModel({
        name: "MyName",
        timestamp: "454951351"
    })

    // call save function on newly created document

    newDocument.save(function(err, response) {
        console.log(response); // response contains the stored object data
    })

}) // on open event block ended
route1.get('/', function(req, res) { // serve upload page when get request is sent
    console.log(db);
})


module.exports = route1

Console will have following data:

{
    _id: 5 b79a9d87557470350704861,
    name: 'MyName',
    timestamp: '454951351',
    date: 2018 - 08 - 19 T17: 33: 12.953 Z,
    __v: 0
}

Leave a Reply

Your email address will not be published. Required fields are marked *

fifty eight − 57 =