Sunday, July 16, 2017

Mongoose

Mongoose
1) npm -v
2) mongo --version
 3)then create these folders

4) npm install --save-dev nodemon 5) npm install express --save
 6) 
Open the server.js file and type/copy the code below into it
var express = require('express'), app = express(), port = process.env.PORT || 3000; app.listen(port); console.log('todo list RESTful API server started on: ' + port);
 7)  npm run start
 8) 
npm install mongoose --save
 9) 
open the todoListModel.js file in your api/models folder and type the following code into the file and save.
'use strict'; var mongoose = require('mongoose'); var Schema = mongoose.Schema; var TaskSchema = new Schema({ name: { type: String, Required: 'Kindly enter the name of the task' }, Created_date: { type: Date, default: Date.now }, status: { type: [{ type: String, enum: ['pending', 'ongoing', 'completed'] }], default: ['pending'] } }); module.exports = mongoose.model('Tasks', TaskSchema);
10) Get Put Delete Update
'use strict'; var mongoose = require('mongoose'), Task = mongoose.model('Tasks'); exports.list_all_tasks = function(req, res) { Task.find({}, function(err, task) { if (err) res.send(err); res.json(task); }); }; exports.create_a_task = function(req, res) { var new_task = new Task(req.body); new_task.save(function(err, task) { if (err) res.send(err); res.json(task); }); }; exports.read_a_task = function(req, res) { Task.findById(req.params.taskId, function(err, task) { if (err) res.send(err); res.json(task); }); }; exports.update_a_task = function(req, res) { Task.findOneAndUpdate({_id: req.params.taskId}, req.body, {new: true}, function(err, task) { if (err) res.send(err); res.json(task); }); }; exports.delete_a_task = function(req, res) { Task.remove({ _id: req.params.taskId }, function(err, task) { if (err) res.send(err); res.json({ message: 'Task successfully deleted' }); }); };

No comments:

Post a Comment