Create API Connecting to MongoDB Part 2 create products and schema

This Article is a continuation of  the Article create API Connecting to MongoDB Part 1

In this Article we  will concentrate on creating the below :

  • Product
  • Schema

First Create a File Call Model

you can call it what ever you want

 

Create Product .JS

Create a Constructor for the Product.JS……..

and then export it to the mongoose module

The Code

 

var mongoose = require ('mongoose');
var Schema = mongoose.Schema;


var product = new Schema({
    
    title:String,
    price:Number,
    likes:Number
    
    
});

module.exports= mongoose.model('Product',product);

 

Create wishList .JS

Create a Constructor for the wishList.JS……..

and then export it to the mongoose module

 

The Code


var mongoose = require ('mongoose');
var schema = mongoose.Schema;


var ObjectId = mongoose.Schema.Types.ObjectId;

var wishList = new Schema({
    
    title: {type:String,default:"Another Wish List"}
    products :[{type:objectId,ref:'Product'}]
    
   
});

module.exports = mongoose.model('WishLict',wishList);



 

Import or Call out product.js and wishlist.js in Server.js

The Code

 

var express = require('express');
var app =express();
var bodyParser =require('body-parser');
var mongoose =require('mongoose');


var Product =require('./model/product');
var WishList =require('./model/wishlist');


app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));

app.listen(3000,function(){
    
    console.log("Shop API running");
    
});

Leave a Reply

Your email address will not be published. Required fields are marked *

three × 1 =