Mongoose + MongoDB

<h3 class="entry-title">Mongoose + MongoDB</h3>
Posted on




Running an Update Operation on All Post documents

The following example is a basic scaffold for connecting to MongoDB and running an operation against a collection.

const mongoose= require('mongoose');
mongoose.connect('mongodb://localhost/my-db');
mongoose.Promise = Promise;
const db = mongoose.connection;
require('./post.model');

const Post = mongoose.model('Post');

db.on('error', console.error.bind(console, 'connection error:'));

db.once('open', function() {
   // Mark All Posts as published
   Post.update({}, { "$set": { "published": true }} ,{multi: true} )
    .then( res => {
        console.log(res);
        process.exit(0)
    })
    .catch(err => {
      console.log('err', err);
      process.exit(0)
    });
});