Posts

Showing posts with the label Mongoose

Bulk Upsert In MongoDB Using Mongoose

Answer : Not in "mongoose" specifically, or at least not yet as of writing. The MongoDB shell as of the 2.6 release actually uses the "Bulk operations API" "under the hood" as it were for all of the general helper methods. In it's implementation, it tries to do this first, and if an older version server is detected then there is a "fallback" to the legacy implementation. All of the mongoose methods "currently" use the "legacy" implementation or the write concern response and the basic legacy methods. But there is a .collection accessor from any given mongoose model that essentially accesses the "collection object" from the underlying "node native driver" on which mongoose is implemented itself: var mongoose = require('mongoose'), Schema = mongoose.Schema; mongoose.connect('mongodb://localhost/test'); var sampleSchema = new Schema({},{ "strict": false }); va...

Check Mongoose Connection State Without Creating New Connection

Answer : Since the mongoose module exports a singleton object, you don't have to connect in your test.js to check the state of the connection: // test.js require('./app.js'); // which executes 'mongoose.connect()' var mongoose = require('mongoose'); console.log(mongoose.connection.readyState); ready states being: 0: disconnected 1: connected 2: connecting 3: disconnecting I use this for my Express Server mongoDB status, where I use the express-healthcheck middleware // Define server status const mongoose = require('mongoose'); const serverStatus = () => { return { state: 'up', dbState: mongoose.STATES[mongoose.connection.readyState] } }; // Plug into middleware. api.use('/api/uptime', require('express-healthcheck')({ healthy: serverStatus })); Gives this in a Postman request when the DB is connected. { "state": "up", "dbState": "conne...