How to use the createConnection function from mongoose
Find comprehensive JavaScript mongoose.createConnection code examples handpicked from public code repositorys.
mongoose.createConnection creates a new Mongoose connection to a MongoDB database.
GitHub: agco/harvesterjs
55 56 57 58 59 60 61 62 63 64
connectionString, _.cloneDeep(gooseOpt) ); this.db.on('error', handleDbError); this.oplogDB = mongoose.createConnection( oplogConnectionString, _.cloneDeep(gooseOpt) ); this.oplogDB.on('error', handleDbError);
+ 11 other calls in file
199 200 201 202 203 204 205 206 207 208
```js var mongoose = require('mongoose'); var Grid = require('gridfs-stream'); var conn = mongoose.createConnection(..); conn.once('open', function () { var gfs = Grid(conn.db, mongoose.mongo); // all set!
+ 5 other calls in file
How does mongoose.createConnection work?
mongoose.createConnection is a function in the Mongoose library for creating a new database connection, which can be used to interact with the database using Mongoose's object modeling and query building features. When you call mongoose.createConnection(), you pass in a MongoDB connection string and any additional options you want to use, and it returns a new Mongoose Connection object that you can use to create and interact with models, documents, and queries. The new connection is separate from the default connection used by mongoose.connect(), so you can use multiple connections in the same application if necessary.
6 7 8 9 10 11 12 13 14 15
EventEmitter.call(this); var self = this; var readyCount = 0; this.db = mongoose.createConnection(mongoUrl) .on('connected', function() { logger.log({ type: 'info', msg: 'connected', service: 'mongodb' }); ready(); })
+ 7 other calls in file
153 154 155 156 157 158 159 160 161 162
can use `conn.transaction()`: ```javascript const mongoose = require('mongoose'); const conn = mongoose.createConnection(process.env.MONGODB_URI); conn.transaction(async function executor() { // ... }); ```
+ 3 other calls in file
Ai Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
const mongoose = require("mongoose"); // create a connection to a MongoDB database const uri = "mongodb://localhost/mydatabase"; const options = { useNewUrlParser: true, useUnifiedTopology: true }; const db = mongoose.createConnection(uri, options); // define a schema for a "users" collection const userSchema = new mongoose.Schema({ name: String, age: Number, email: String, }); // create a "users" model based on the schema const User = db.model("User", userSchema); // use the model to create a new document in the collection const newUser = new User({ name: "John Doe", age: 30, email: "johndoe@example.com", }); newUser .save() .then(() => console.log("User saved to database")) .catch((err) => console.error(err));
In this example, mongoose.createConnection is used to create a connection to a MongoDB database. The connection is then used to define a schema for a "users" collection, create a model based on that schema, and save a new document to the collection using the model.
55 56 57 58 59 60 61 62 63 64
```javascript // Works mongoose.createConnection().then(conn => conn.model('Test', schema)); // Also works const conn = mongoose.createConnection(); conn.model('Test', schema); ``` Mongoose does this by deleting `conn.then()` before resolving the promise, so if you try to call `.then()` **after** the connection has successfully connected, you will get an error:
+ 5 other calls in file
GitHub: althjs/redisfire
32 33 34 35 36 37 38 39 40 41
return connections[projectName]; } else { var projectConf = _redis.getProjectConf(projectName); console.log('@@ mongodb connect: ' + projectName + ' with ' + projectConf.auth + ' collection as ', mongo_connection_string + ' database'); var conn = mongoose.createConnection(mongo_connection_string); var Auth = conn.model(projectConf.auth, redisfire_auth_schema); connections[projectName] = Auth; return connections[projectName]; }
41 42 43 44 45 46 47 48 49 50
```javascript var mongoose = require('mongoose') var mongoomise = require('mongoomise') var connection = mongoose.createConnection('..') //load models var User = connection.model('User', UserSchema) var UserX = mongoose.model('User', UserSchema)
+ 11 other calls in file
GitHub: ForestAdmin/lumber
10 11 12 13 14 15 16 17 18 19
const connections = {}; const db = {}; databasesConfiguration.forEach((databaseInfo) => { {{#if isMongoDB}} const connection = Mongoose.createConnection(databaseInfo.connection.url, databaseInfo.connection.options); {{else}} const connection = new Sequelize(databaseInfo.connection.url, databaseInfo.connection.options); {{/if}} connections[databaseInfo.name] = connection;
+ 9 other calls in file
GitHub: agco/harvesterjs
156 157 158 159 160 161 162 163 164
poolSize: 1, keepAlive: 1, }, }; var db = mongoose.createConnection(oplogConnectionString, gooseOpt); db.on('error', function(err) { that.handleError(err, res, docStream); });
32 33 34 35 36 37 38 39 40 41 42
var storage; var upload; const mongoURI = util.mongoUrlFiles(); console.log(nameFile + '| mongoURI :', JSON.stringify(mongoURI)); logger.info(nameFile + " | mongoURI: " + JSON.stringify(mongoURI)); //const connection = mongoose.createConnection(mongoURI, { useNewUrlParser: true }); mongoose .connect(mongoURI, { // useCreateIndex: true,
+ 4 other calls in file
GitHub: Anabil-Baruah/famesbook
15 16 17 18 19 20 21 22 23 24 25 26
const ObjectId = mongodb.ObjectId const { formatDate } = require('../formatDate') require('dotenv').config() let gfs, gridfsBucket; const conn = mongoose.createConnection(process.env.MONGO_URL_FILE_UPLOADS) conn.once('open', () => { gridfsBucket = new mongoose.mongo.GridFSBucket(conn.db, { bucketName: 'uploads'
+ 4 other calls in file
8 9 10 11 12 13 14 15 16 17 18
const path = require('path'); const User = require('../model/User'); require('dotenv').config(); const mongoURI = process.env.DATABASE_URI; const conn = mongoose.createConnection(mongoURI, { useNewUrlParser: true, useUnifiedTopology: true, dbName: process.env.DB_NAME });
2 3 4 5 6 7 8 9 10 11 12 13 14
describe('toJSON plugin', () => { let connection; beforeEach(() => { connection = mongoose.createConnection(); }); it('should replace _id with id', () => { const schema = mongoose.Schema();
mongoose.model is the most popular function in mongoose (2160 examples)