Everything You Need to Know About Mongoose

ODM(Object Data Modeling) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.

A tool which provide data modeling and help connecting to mongoDB

Connect Node JS to MongoDB

index.js

const mongoose = require('mongoose');

app.get('/mongodb', async (req, res) => {
    await mongoose.connect('mongodb://localhost/voyage', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: true,
        useCreateIndex: true
    });

		res.send('ok');
})

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/ed964253-edea-44aa-9eb4-759b78f9e2c4/Screen_Shot_2021-06-25_at_6.14.30_PM.png

Modeling

to show one product

  1. image
  2. name
  3. price
  4. category

https://s3-us-west-2.amazonaws.com/secure.notion-static.com/1020c69b-a7a7-4b77-86c1-b7cd926d49a5/Screen_Shot_2021-06-25_at_6.24.36_PM.png

index.js

const mongoose = require('mongoose');

app.get('/mongodb', async (req, res) => {
    await mongoose.connect('mongodb://localhost/voyage', {
        useNewUrlParser: true,
        useUnifiedTopology: true,
        useFindAndModify: true,
        useCreateIndex: true
    }); // options

    const { Schema } = mongoose;
    const goodsSchema = new Schema({
        goodsId: {type: Number, required: true, unique: true},
        name: {type: String, required: true, unique: true},
        thumbnailUrl: {type: String},
        category: {type: String},
        price: {type: Number}
    });

    let Goods = mongoose.model("Goods", goodsSchema);

    await Goods.create({
        goodsId: 1,
        name: "dinner",
        thumbnailUrl: "<https://purewows3.imgix.net/images/articles/2019_04/one-pan-spaghetti-meatballs-recipe-290.jpg?auto=format,compress&cs=strip>",
        category: "food",
        price: 20000

    });

    res.send('OK');
});