INFO 30005
Web Information Technologies
Mongoose.js
Copyright By PowCoder代写 加微信 powcoder
This lecture
• Object-Document Modelling (ODM)
• install/include Mongoose in your app
• connect to your MongoDB server
• simple and complex schemas
• simple and complex database queries
• demo app (which you can download)
Object Document Modeler (ODM )
your Node program
MongoDB server
Mongoose features
• makes various MongoDB tasks easier
• manage data using object-like methods
• use schemas to validate user data [?]
• maintain database schemas in app code
• types, ranges, enum, required, unique, defaults
• custom / npm validators (email etc)
• population (similar to ‘join’, without ref. integrity)
Data Model
_id: ObjectId, email: string, password: string, nameFamily: string, nameGiven: string, gender: string, yearBorn: number, favourites: [
{foodId: ObjectId} ],
{foodId: ObjectId
when: date} ]
_id: ObjectId, name: string, photo: string, description: string, vegan: boolean, organic: boolean, calories: number, fat: number, protein: number
Using the demo
• mkdir [directory]
• npm init –y
• npm install mongoose
• npm install express
• git init, etc
• copy code from Canvas
Demo: setup Mongoose
// setup Mongoose
const mongoose = require(‘mongoose’)
let connectionURL = ‘mongodb://localhost/FoodBuddy’ if (‘PORT’ in process.env) {
connectionURL = ‘mongodb+srv://**************/FoodBuddy?retryWrites=true&w=majority’ }
mongoose.connect(connectionURL, {useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, dbName: ‘FoodBuddy’})
const db = mongoose.connection
// event handlers
db.on(‘error’, console.error.bind(console, ‘connection error:’)) db.once(‘open’, () => {
console.log(‘connected to Mongo’)
Demo: simple schema
// define the Food schema
const foodSchema = new mongoose.Schema({
name: {type: String, required: true, unique: true}, photo: String,
description: String,
vegan: {type: Boolean, default: false},
organic: {type: Boolean, default: false},
calories: {type: Number, min: 0},
fat: {type: Number, min: 0},
protein: {type: Number, min: 0}
Demo: complex schema
// define the Favourite schema
const favouriteSchema = new mongoose.Schema({
foodId: {type: mongoose.Schema.Types.ObjectId, ref: ‘Food’}
// define the Eaten schema
const eatenSchema = new mongoose.Schema({
foodId: { type: mongoose.Schema.Types.ObjectId, ref: ‘Food’ }, when: {type: Date, default: Date.now}
const userSchema = new mongoose.Schema({
email: {type: String, required: true, unique: true}, password: {type: String, required: true}, nameFamily: {type: String, required: true}, nameGiven: String,
gender: String,
yearBorn: {type: Number, min: 1900},
favourites: [favouriteSchema],
eaten: [eatenSchema]
Demo: simple queries
//*** FOOD ROUTES STARTS HERE ***//
// get all foods
app.get(‘/foods’, async (req, res) => {
result = await Food.find( {}, {name: true, description: true, _id:false} ) res.send(result)
// get one food – user specifies its name
app.get(‘/foods/:name’, async (req, res) => {
result = await Food.findOne( {name: req.params.name}, {} ) res.send(result)
Demo: queries with subdocuments
// get Alice to favourite a food
app.get(‘/AliceFavourite/:food’, async (req, res) => { // find Alice
let thisUser = await User.findOne( {nameGiven: ‘Alice’}) // find food
let favouriteFood = await Food.findOne( {name: req.params.food})
// add food to Alice’s Favourites list
favouriteRecord = new Favourite({foodId: favouriteFood._id}) thisUser.favourites.push(favouriteRecord)
// save Alice’s updated record to database
await thisUser.save()
// show the new Alice record
result = await User.findOne( {nameGiven: ‘Alice’})
res.send(result) })
Demo: handling http POST
// insert new food into collection
app.post(‘/addFood’, async (req, res) => { // using POST for Postman demo
const newFood = new Food({
name: req.body.name,
photo: req.body.photo, description: req.body.description, vegan: req.body.vegan,
organic: req.body.organic, calories: req.body.calories, fat: req.body.fat,
protein: req.body.protein
newFood.save( (err, result) => { // callback-style error-handler
if (err) res.send(err)
return res.send(result) })
Using Postman
• set up requests to test your POST routes
• export your requests and submit with project
• demo code is available on Canvas
• docs at https://mongoosejs.com/docs/guide.html
• excellent book: Mongoose for Application Development
• you’ll use Mongoose in the week 6 workshop
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com