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:
- drop the database
- create a collection
- write some data to a collection
- query a collection
- drop a collection
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.collectionand then you caninsertorremoveordropor 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.