Mongoose

Introduction

  • It is similar with sequalize, is a object document mapping library

  • It operate by using command behind the scene

Connect to MongoDB

mongoose
  .connect(
    'mongodb+srv://maximilian:9u4biljMQc4jjqbe@cluster0-ntrwp.mongodb.net/shop?retryWrites=true'
  )
  .then(result => {
    app.listen(3000);
  })
  .catch(err => {
    console.log(err);
  });
const mongoose = require('mongoose');

const Schema = mongoose.Schema;

// decrease the data flexbility based the need
const productSchema = new Schema({
  title: {
    type: String,
    required: true
  },
  price: {
    type: Number,
    required: true
  },
  description: {
    type: String,
    required: true
  },
  imageUrl: {
    type: String,
    required: true
  },
  userId: {
    type: Schema.Types.ObjectId,
    // refer to user collection
    ref: 'User',
    required: true
  }
});

// Define which collection is mapped to
module.exports = mongoose.model('Product', productSchema);

CRUD Operation

const Product = require('../models/product');


// Create
const product = new Product({
 title: title,
 price: price,
 description: description,
 imageUrl: imageUrl,
 // automatically pick _id from user object
 userId: user 
});

product.save();


// Read 
 Product.find()
 .select("title price -_id") // filter the field
 .populate("userId", "name") // get the user based on userId and  filter user field
 .then(products => {
  // ...
 })
 .catch(err=> {
  // ...
 });
 
 Product.findById("id")
 .then(product => {
  // ...
 })
 .catch(err=> {
  // ...
 });
 
 // Update
Product.findById("id")
 .then(product => {
  product.title = "title";
  product.save();
 })
 .catch(err=> {
  // ...
 });
 
 
 // Delete
 Product.findByIdAndRemove("id")
 

Last updated

Was this helpful?