How to do raw mongodb operations in mongoose?

You can run mongodb commands using the native NodeJS driver by using mongoose.connection.db. This accesses the NodeJS MongoDB driver, and you don’t need to create a mongoose model.

An insert

mongoose.connection.db.collection('userCollection').insert({
  username: 'captain1',
  firstName: 'Steve',
  lastName: 'Rogers', 
});

An update

mongoose.connection.db.collection('userCollection').update(
  {someFilterProperty: true},
  {$set: {
     siteId: new mongoose.mongo.ObjectId('56cb91bdc5946f14678934ba'),
     hasNewSiteId: true}},
  {multi: true});
});

You can send every command specific to that database using the database connection db reference mongoose.connection.db.

This is the mongoose API doc: http://mongoosejs.com/docs/api.html#connection_Connection-db

Important: Note some of the options in the NodeJS driver are different than the options in MongoDB shell commands. For example findOneAndUpdate() uses returnOriginal instead of returnNewDocument. See here and here for more on this.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)