Skip to content

Instantly share code, notes, and snippets.

@crizstian
Created January 29, 2017 20:03
Show Gist options
  • Save crizstian/48bf8168b4cff725d7227c227673005e to your computer and use it in GitHub Desktop.
Save crizstian/48bf8168b4cff725d7227c227673005e to your computer and use it in GitHub Desktop.
Example of retrieving data from mongoDB
// more code above
const getCinemasByCity = (cityId) => {
return new Promise((resolve, reject) => {
const cinemas = []
const query = {city_id: cityId}
const projection = {_id: 1, name: 1}
// example of making a find query to mongoDB,
// passign a query and projection objects.
const cursor = db.collection('cinemas').find(query, projection)
const addCinema = (cinema) => {
cinemas.push(cinema)
}
const sendCinemas = (err) => {
if (err) {
reject(new Error('An error occured fetching cinemas, err: ' + err))
}
resolve(cinemas)
}
cursor.forEach(addCinema, sendCinemas)
})
}
const getCinemaById = (cinemaId) => {
return new Promise((resolve, reject) => {
const query = {_id: new ObjectID(cinemaId)}
const projection = {_id: 1, name: 1, cinemaPremieres: 1}
const response = (err, cinema) => {
if (err) {
reject(new Error('An error occuered retrieving a cinema, err: ' + err))
}
resolve(cinema)
}
// example of using findOne method from mongodb,
// we do this because we only need one record.
db.collection('cinemas').findOne(query, projection, response)
})
}
const getCinemaScheduleByMovie = (options) => {
return new Promise((resolve, reject) => {
const match = { $match: {
'city_id': options.cityId,
'cinemaRooms.schedules.movie_id': options.movieId
}}
const project = { $project: {
'name': 1,
'cinemaRooms.schedules.time': 1,
'cinemaRooms.name': 1,
'cinemaRooms.format': 1
}}
const unwind = [{ $unwind: '$cinemaRooms' }, { $unwind: '$cinemaRooms.schedules' }]
const group = [{ $group: {
_id: {
name: '$name',
room: '$cinemaRooms.name'
},
schedules: { $addToSet: '$cinemaRooms.schedules.time' }
}}, { $group: {
_id: '$_id.name',
schedules: {
$addToSet: {
room: '$_id.room',
schedules: '$schedules'
}
}
}}]
const sendSchedules = (err, result) => {
if (err) {
reject('An error has occured fetching schedules by movie, err: ' + err)
}
resolve(result)
}
// example of using a aggregation method from mongoDB
// we difine our pipline above, we are using also ES6 spread operator
db.collection('cinemas').aggregate([match, project, ...unwind, ...group], sendSchedules)
})
}
// more code below
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment