简体   繁体   中英

How Can I populate some Collections in MongoDB only in the first time

I'm using NodeJs as backend and MongoDB as a database along with mongoose .

I want to populate one of my collections named Users only for the first time that the application runs.

My goal is to add one user to users collection automatically in the first time that application run.

( this subject is known as migration in ASP.NET And EntityFramework ).

How can I achieve that in Nodejs?

Well that's kindda easy, you just need to wait for mongoose to connect to your database then put your code in the event listener for the database connection.

check out the example straight out of mongoose docs

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {useNewUrlParser: true});
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
  // You can put your code here
});

NOTE: there might be connection interruption and mongodb gets disconnected and reconnected (this happens manually), you need to put a flag to make sure you don't populate your database unwillingly after reconnection.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM