How to use the connection function from mongoose
Find comprehensive JavaScript mongoose.connection code examples handpicked from public code repositorys.
mongoose.connection is an object in the Mongoose library that represents the connection to a MongoDB database.
50 51 52 53 54 55 56 57 58
result: "1-0"}); g1.save(function(err) {}); g2.save(function(err) {}); mongoose.connection.close(); }); /* Init elastic search server */
GitHub: dstroot/skeleton
40 41 42 43 44 45 46 47 48 49
/** * Configure Mongo Database */ mongoose.connect(config.mongodb.url); var db = mongoose.connection; // Use Mongo for session store config.session.store = new MongoStore({ mongooseConnection: db,
How does mongoose.connection work?
The mongoose.connection object is a part of the Mongoose library, which is an Object Data Modeling (ODM) tool for MongoDB. When you create a new Mongoose application, you typically use the mongoose.connect method to establish a connection to a MongoDB database. This method returns a mongoose.connection object that represents the connection. You can use the mongoose.connection object to interact with the database by calling its methods. For example, you can use the model method to define a new data model and register it with Mongoose, or the collection method to get a reference to a collection in the database. The mongoose.connection object also emits various events that you can use to track the status of the connection. For example, you can listen for the connected event to be notified when the connection is successfully established, or the error event to be notified when an error occurs. You can also use the mongoose.connection object to manage transactions, which allow you to perform multiple database operations as part of a single atomic transaction. When you are finished using the mongoose.connection object, you can call its close method to close the connection to the database. Overall, the mongoose.connection object provides a powerful way to interact with a MongoDB database using Mongoose.
17 18 19 20 21 22 23 24 25
} }); connection = mongoose.connection; mongoose.Promise = global.Promise; mongoose.connection.on('error', (err) => { console.log('Error connecting to MongoDB: ' + err); callback(err, false); });
+ 5 other calls in file
22 23 24 25 26 27 28 29 30
mongoose.connection.on('error', (err) => { console.log('Error connecting to MongoDB: ' + err); callback(err, false); }); mongoose.connection.once('open', () => { console.log('We have connected to mongodb'); callback(null, true); });
+ 5 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 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46
const mongoose = require("mongoose"); // Connect to a MongoDB database mongoose.connect("mongodb://localhost/mydatabase"); // Get a reference to the default connection const db = mongoose.connection; // Define a new data model and register it with Mongoose const schema = new mongoose.Schema({ name: String, age: Number, }); const Person = mongoose.model("Person", schema); // Insert a new document into the database const john = new Person({ name: "John", age: 30 }); john.save(function (err, result) { if (err) { console.log(err); } else { console.log(result); } }); // Retrieve documents from the database Person.find(function (err, people) { if (err) { console.log(err); } else { console.log(people); } }); // Listen for the connected event to be notified when the connection is established db.on("connected", function () { console.log("Connected to MongoDB"); }); // Listen for the error event to be notified when an error occurs db.on("error", function (err) { console.log("MongoDB error:", err); }); // Close the connection to the database when finished db.close();
In this example, we first require the mongoose module and use the mongoose.connect method to establish a connection to a MongoDB database. We then use the mongoose.connection object to define a new data model for a Person object and register it with Mongoose using the mongoose.model method. We also insert a new Person object into the database and retrieve all Person objects from the database using the find method. We listen for the connected and error events on the mongoose.connection object to be notified when the connection is established and when an error occurs, respectively. Finally, we call the close method on the mongoose.connection object to close the connection to the database when finished.
GitHub: dashersw/mogollar
16 17 18 19 20 21 22 23 24 25
}, mutations: {}, actions: { async connect({ state, dispatch }, connectionString) { await mongoose.connect(connectionString, { useNewUrlParser: true }) state.connection = mongoose.connection await dispatch('getDatabases') }, async getDatabases({ state }) { try {
+ 3 other calls in file
5 6 7 8 9 10 11 12 13 14
if(!connectionString) { console.error('MongoDB connection string missing!') process.exit(1) } mongoose.connect(connectionString, { useNewUrlParser: true }) const db = mongoose.connection db.on('error', err => { console.error('MongoDB error: ' + err.message) process.exit(1) })
+ 3 other calls in file
5 6 7 8 9 10 11 12 13 14
*/ mongoose.Promise = global.Promise function connectDatabase(uri) { return new Promise((resolve, reject) => { mongoose.connection .on('error', error => reject(error)) .on('close', () => console.log('Database connection closed.')) .once('open', () => resolve(mongoose.connections[0])) mongoose.connect(uri)
6 7 8 9 10 11 12 13 14 15
mongoose.connect(config.mongodb.connectionString || 'mongodb://' + config.mongodb.user + ':' + config.mongodb.password + '@' + config.mongodb.server +'/' + config.mongodb.database, { server: { auto_reconnect : true, poolSize: 100 } }, function(err) { if (err) { console.error('Failed to connect to mongo on startup - retrying in 5 sec', err); setTimeout(connectWithRetry, 5000); } else { mongoose.connection.on('open', function (err) { mongoose.connection.on('error', function(err) { console.log("Mongo collection failed, trying to reconnect"); }); mongoose.connection.db.admin().serverStatus(function(err, data) {
+ 7 other calls in file
18 19 20 21 22 23 24 25 26
return mongoose; }; function cleanup() { mongoose.connection.close(function () { process.exit(0); }); }
236 237 238 239 240 241 242 243 244 245
Tallettaminen tapahtuu metodilla _save_. Metodi palauttaa <i>promisen</i>, jolle voidaan rekisteröidä _then_-metodin avulla tapahtumankäsittelijä: ```js note.save().then(result => { console.log('note saved!') mongoose.connection.close() }) ``` Kun olio on tallennettu kantaan, kutsutaan _then_:in parametrina olevaa tapahtumankäsittelijää, joka sulkee tietokantayhteyden komennolla <code>mongoose.connection.close()</code>. Ilman yhteyden sulkemista ohjelman suoritus ei pääty.
+ 7 other calls in file
GitHub: mayeaux/nodetube
67 68 69 70 71 72 73 74 75 76
// }); // // // mongoose.set('debug', true); // // // mongoose.connection.on('error', (err) => { // console.error(err); // console.log('%s MongoDB connection error. Please make sure MongoDB is running.', chalk.red('✗')); // process.exit(); // });
+ 4 other calls in file
GitHub: invertase/nlp.js-app
49 50 51 52 53 54 55 56 57 58
return new Promise((resolve, reject) => { mongoose.connect( this.url, { useNewUrlParser: true } ); const db = mongoose.connection; db.on('error', () => reject(new Error('Connection error'))); db.once('open', () => resolve()); }); }
GitHub: anlix-io/flashman
234 235 236 237 238 239 240 241 242 243
hasInitialized = true; return; } const setup = async () => { if (!db) db = Mongoose.connection.db; audits = db.collection('audits'); const d = Date.now()-5*60*1000; // milliseconds at 5 minutes ago. await audits.updateMany(
+ 7 other calls in file
552 553 554 555 556 557 558 559 560 561
/** * Pour l'historique du plan de transport, permet de récupérer la liste des options des filtres */ router.get("/patches/filter-options", passport.authenticate("referent", { session: false, failWithError: true }), async (req, res) => { try { const db = mongoose.connection.db; const busline = { op: await db.collection("lignebus_patches").distinct("ops.op"), path: await db.collection("lignebus_patches").distinct("ops.path"), user: await db.collection("lignebus_patches").distinct("user"),
193 194 195 196 197 198 199 200 201 202
value: 3, label: "Disconnecting", css: "text-warning" } ]; let mongostate = mongoose.connection.readyState; ret.setMessages("Mongodb state"); ret.setData(dbState.find(f => f.value == mongostate)); res.status(200); ret.setSuccess(true);
+ 4 other calls in file
0 1 2 3 4 5 6 7 8 9
var mongoose = require('mongoose'); var userModel = require('./models/user'); var STRIPE_PRODUCTION = false; mongoose.connect(process.env.MONGO_SRV, { useNewUrlParser: true, useUnifiedTopology: true }); if(process.env.PRODUCTION == "true") { mongoose.connection.useDb('brainbase'); } function generateRandomString(length) { var text = ""; var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvw123456789";
+ 9 other calls in file
GitHub: konstantin0s/babySteps
114 115 116 117 118 119 120 121 122 123 124 125
}); //close mongodb process.on('SIGINT', function() { mongoose.connection.close(function() { console.log('Mongoose disconnected on app termination'); process.exit(0); }); });
GitHub: qasim2020/playground
67 68 69 70 71 72 73 74 75 76
cookie: { maxAge: 20 * 60 * 1000, }, rolling: true, store: new MongoStore({ mongooseConnection: mongoose.connection }) }), express.static(__dirname+'/static'), passport.initialize(),
+ 3 other calls in file
GitHub: bicsak/dpl4server
45 46 47 48 49 50 51 52 53 54 55 56
const mysqlDb = makeDb( mysqlConfig ); async function run(hc) { try { mongoose.connection.on('connected', () => { console.log('Mongoose connected to DB Cluster'); }); mongoose.connection.on('error', (error) => { console.error(error.message);
+ 4 other calls in file
33 34 35 36 37 38 39 40 41 42 43
// useUnifiedTopology: true // }); mongoose.connect(process.env.DATABASE_URL, { useNewUrlParser: true, useUnifiedTopology: true }); mongoose.set("useCreateIndex", true); const connection = mongoose.connection; connection.once('open', () => { console.log("MongoDB database connection established successfully"); });
mongoose.model is the most popular function in mongoose (2160 examples)