USING NODEJS WITH MONGOOSE
Andrew College Boston University
Mongoose is an object modeling tool designed to work with Express JS and Node.
Copyright By PowCoder代写 加微信 powcoder
WHAT IS MONGOOSE?
Mongoose is an Object Document Mapper (“ODM”)
Mongoose allows you to define objects with typed properties.
Developers continue using Javascript/JSON working with the data.
Lower learning curve – leverage existing skill sets
Less technologies used in your stack – less complexity and easier maintenance
Models are defined using a Schema.
A schema allows you to define the fields stored in each document along any possible validation requirements and defaults.
DEFINITION OF A SCHEMA
VALID SCHEMA
DATA TYPES
String Number Date Buffer Boolean Mixed ObjectId Array Decimal128 Map
AS DEFINITIONS (OR DTD)
Think of it as..
Schema is the configuration object for your data models.
VALID SCHEMA TYPES
Example using
SCHEMA TYPES
THE OBJECTID
Represents specific instance of a model in your database. It is a unique ID.
CUSTOMIZE HOW THE
DATA STORED/RETRIEVED
MODELING YOUR
Models are created from your Schema using the model() function.
OBJECT REFERENCES
(MODELS WITHIN MODELS)
const addressSchema = new Schema({ city: String,
street: String,
houseNumber: String });
mongoose.model(‘address’, addressSchema, ‘address’)
OBJECT REFERENCES
(MODELS WITHIN MODELS)
const contactInfo = new Schema({ cell: [Number],
email: [String],
address: {
type: mongoose.Schema.Type.ObjectId, ref: ‘address’
const userMdl = mongoose.model(‘User’, UserSchema);
const addressMdl = mongoose.model(‘Address’, AddressSchema);
module.exports = { User : userMdl,
Address: addressMdl }
STORE IN /MODEL
Recommendation: Have all your
model definitions in one folder,
called /model.
// In your application, you can reference your Model(s) by
const {User, Address} = require(‘/models’);
BASIC CONNECT
const mongoose = require(‘mongoose’);
mongoose.connect( ‘mongodb://localhost:27017/db’, {useNewUrlParser: true}
CONNECTION
EVENTS mongoose.connection.on(‘disconnected’, () => {
console.log(‘message goes here’); });
mongoose.connection.on(‘connected’, () => { console.log(‘message goes here’);
var Tank = mongoose.model(‘Tank’, yourSchema); var small = new Tank({ size: ‘small’ })
small.save(function (err) {
if (err) { /* handle the error */ } …
程序代写 CS代考 加微信: powcoder QQ: 1823890830 Email: powcoder@163.com