I've set up my expressjs server and mongoDB (using the mongoDB native driver and not mongoose). I want to check for existing documents in the database and add some fixture documents when the server starts, but I'm unsure where to do that.
Something along the lines of:
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