1+ const express = require ( "express" ) ;
2+ const app = express ( ) ;
3+ const mongoose = require ( "mongoose" ) ;
4+ const Schema = mongoose . Schema ;
5+ const url = process . env . MONGODB || 'mongodb://localhost:27017/apiDB' ;
6+ const port = process . env . PORT || 8080 ;
7+
8+
9+ const noteSchema = new Schema ( {
10+ text : String ,
11+ priority : String ,
12+ createdAt : Date ,
13+ updatedAt : Date ,
14+ } ) ;
15+
16+ noteSchema . virtual ( 'id' ) . get ( function ( ) {
17+ return this . _id . toHexString ( ) ;
18+ } ) ;
19+
20+ noteSchema . set ( 'toJSON' , {
21+ virtuals : true
22+ } ) ;
23+
24+ const Note = mongoose . model ( 'Note' , noteSchema ) ;
25+
26+
27+ mongoose . connect ( url , { useNewUrlParser : true , useUnifiedTopology : true } ) ;
28+ var db = mongoose . connection ;
29+ db . on ( 'error' , console . error . bind ( console , 'connection error:' ) ) ;
30+ db . once ( 'open' , function ( ) {
31+ console . log ( 'MONGODB CONNECTED' )
32+ } ) ;
33+
34+ app . use ( express . json ( ) )
35+
36+ app . post ( "/notes" , function ( req , res ) {
37+ const note = new Note ( req . body ) ;
38+ note . save ( ) . then ( ( doc ) => {
39+ res . json ( doc )
40+ } )
41+ } )
42+
43+ app . get ( "/notes" , function ( req , res ) {
44+ Note . find ( { } , function ( err , docs ) {
45+ res . json ( docs ) ;
46+ } )
47+ } )
48+
49+ app . put ( "/notes/:id" , function ( req , res ) {
50+
51+ Note . findOneAndReplace ( { _id :req . params . id } , req . body , {
52+ returnDocument :'after'
53+ } ) . then ( ( doc ) => {
54+ res . json ( doc )
55+ } )
56+ } )
57+
58+ app . delete ( "/notes/:id" , function ( req , res ) {
59+
60+ Note . findByIdAndDelete ( { _id :req . params . id } ) . then ( ( doc ) => {
61+ res . json ( doc )
62+ } )
63+ } )
64+
65+ app . listen ( port , function ( ) {
66+ console . log ( "server started at :" , port ) ;
67+ } )
0 commit comments