How to do raw mongodb operations in mongoose?

MongodbMongoose

Mongodb Problem Overview


I'm asking this because when I write unit tests, I want to drop the test database and insert some initialize data, and also check the data in mongodb in testing. So I need raw operations to mongodb.

How to do this in mongoose? What I can do now is just create the connection, and not find any document in mongoose's official site.

 var mongoose = require('mongoose');
 mongoose.connect('mongo://localhost/shuzu_test');

 // get the connection
 var conn = mongoose.connection;

But how to:

  1. drop the database
  2. create a collection
  3. write some data to a collection
  4. query a collection
  5. drop a collection

Mongodb Solutions


Solution 1 - Mongodb

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.

Solution 2 - Mongodb

See the section on "Driver Access" in the docs: http://mongoosejs.com/

Basically you can get access to the node-mongodb-native driver by doing YourModel.collection and then you can insert or remove or drop or whatever you need.

There's not a doc, but with this approach you'll get access to everything in here: https://mongoosejs.com/docs/api.html#collection-js

Edit:

In your case you may want to skip using mongoose in your test suite and use the node-mongodb-native directly, or even write a simple mongodb shell script that can be run before your tests start.

Solution 3 - Mongodb

use this to run raw operations in mongoose.

  Model_name.collection.insertMany(array, { ordered: false },function(err, success){
			console.log(success);
		});

Solution 4 - Mongodb

Have encountered same trouble, to cleanup DBs after tests, and actual answer only confused because of absence "code blocks", so dig docs/code once more, for others-time-saving purpose posting this ;)

Mongoose collection extends Mongodb collection

> /*

> interface CollectionBase extends mongodb.Collection {

> Documentation : http://mongodb.github.io/node-mongodb-native/2.1/api/Collection.html

Same goes for the connection: > The Connection class exposed by require('mongoose') is actually the driver's NativeConnection class. connection.js defines a base class that the native versions extend. See: http://mongoosejs.com/docs/api.html#drivers-node-mongodb-native-connection-js

So all "RAW" operations can be performed on collection/connection, assuming that you have

 var connection = mongoose.connection;

then:

1.drop the database:

connection.dropDatabase()

2.create a collection

connection.collection('newcollection') // creates if not exists

3.write some data to a collection

connection.collection('mybenotnewcollection').bulkWrite([
  { insertOne: { whatewer: { you: 'need' } } },
]);

4.query a collection

that's obviously not a question: findAll, find, aggregate, all allowed (see the Docs)

5.drop a collection

connection.collection('notsonewcollection').drop()

Solution 5 - Mongodb

const mongoose = require('mongoose');
mongoose.connect(uri, options);
var db = mongoose.connection;
db.once('open', function () {
  db.collection('collection').find().toArray(function(err, result){
        console.log(result);
  });
}

Solution 6 - Mongodb

The mongoose object has a mongo prototype which gives you access to native mongo driver

mongoose.mongo

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionFreewindView Question on Stackoverflow
Solution 1 - MongodbsteampoweredView Answer on Stackoverflow
Solution 2 - MongodbJamund FergusonView Answer on Stackoverflow
Solution 3 - Mongodbjitendra rajputView Answer on Stackoverflow
Solution 4 - Mongodb2oppinView Answer on Stackoverflow
Solution 5 - MongodbhardyRocksView Answer on Stackoverflow
Solution 6 - MongodbCurious FlowerView Answer on Stackoverflow