首页 文章

expressJS / mongoDB:如何在启动时添加一些夹具mongoDB数据?

提问于
浏览
0

这就是我设置我的expressjs服务器和我的mongoDB(mongoDB本机驱动程序,而不是mongoose)的方法 . 现在我想检查数据库中的一些现有文档,以便在服务器启动时添加一些夹具文档 . 我不明白该怎么做 .

就像是:

const hasAdmin = db.collection('users').findOne({ username: 'admin' })
if (!hasAdmin) {
  // Add some data to collection
}

app.js

const app = express()
const mongoDB = mongodb://localhost:27017/mydb

// Parse application/json
app.use(bodyParser.json())
// Parse application/x-www-form-urlencoded
app.use(bodyParser.urlencoded({
  extended: false
}))
// GraphQL
app.use('/graphql',
  bodyParser.text({ type: 'application/graphql' }),
  graphqlMiddleware,
  graphqlExpress(req => ({
    schema: schema
  }))
)

// Connect to Mongo on start
db.connect(mongodb, (err) => {
  if (err) {
    console.error('Unable to connect to Mongo: ' + err)
    process.exit(1)
  } else {
    app.listen(port, () => {
      console.log('Listening on port ' + port)
    })
  }
})

module.exports = app

1 回答

  • 0

    理论上你可以把它放在任何打开Mongo连接的地方 .

    我建议将与数据库相关的功能提取到一个单独的类中(以及一个单独的文件; separation of concerns) .

    然后,您可以从该类的构造函数中调用最初填充数据库的功能 .

    像这样的东西(这不是工作代码,但应该给你一个想法):

    db-helper.js

    class DbHelper {
        constructor() {
            this.connect();
        }
    
        connect() {
            // establish mongo connection
            mongo.connect("...", (err, db) => {
                this.db = db;
                // then take care of initial filling
                this.ensureDatabaseIsFilled();
            });
    
        }
    
        ensureDatabaseIsFilled() {
            const hasAdmin = this.db.collection('users').findOne({ username: 'admin' })
            if (!hasAdmin) {
                // Add some data to collection
            }
        }
    
        /**
          * Random method that retrieves data from mongo
          */
        getRandomThing() {
            return new Promise((resolve, reject) => {
                this.db.find({...}, (err, result) => resolve(result));
            });
        }
    }
    module.exports = DbHelper;
    

    app.js

    const DbHelper = require('./db-helper');
    const dbHelper = new DbHelper();
    // ....
    app.get('/example', (req, res) => {
        dbHelper.getRandomThing().then(result => res.send(result));
    });
    // ....
    

相关问题