BoilerPlate: Mongoose

Mongoose

const mongoose = require('mongoose'); // getting-started.js

mongoose.connect(“mongodb://localhost:27017/MyDB”, {useNewUrlParser: true}); // connect to MyDB database

const mySchema = new mongoose.Schema ({

 name: String,

 price: {

type: Number,

min: 0,

required: [true, “err message here”]} // can add validation, store as a JS object

 review: String

}) // specify the attributes of a data

const Item = mongoose.model(“Item”, mySchema); // create the collection. Singular form in mongoose model, and mongoose will automatically create a collection with name of “Items”

const item = new Item ({

 name: “Item A”,

 price: 10,

 review: “write your review here

}); // create a new item with Item model

item.save();// add the item to the collection

Item.find(function(err, items){

  if (err) {

    console.log(err);

  } else {

console.log (items); // read all the items in Item Model

items.forEach(function(item){

   console.log(item.name);  // read a certain attribute of all the items

}

  }

} )

const customerSchema = new mongoose.Schema ({

 Fname: String,

 favoriteItem: mySchema // can relate to the defined schema

})

const Customer = mongoose.model(“Customer”, customerSchema);

const customer = new Customer ({

 Fname: “John”,

 favoriteItem: item // refer to the const “item” created above, no “” here.

})

 


0 Comments