node.js - my post request using nodejs express to mongodb database doesn't work strangely? -
i trying post data sever save mongodb. notice request working right couldnt post data mongodb database.
the main code:
// tools used in web development var express = require('express'); var app = express(); var bodyparser = require('body-parser'); var mongoose = require('mongoose'); app.use(bodyparser.json()); genre = require('./models/genre.js'); book = require('./models/book.js'); let conn = mongoose.connection; conn.openuri('mongodb://localhost/bookstore'); conn.on('error', err => console.error('mongodb connection error', err)); conn.on('connected', () => console.info(`connected mongodb`)); conn.on('disconnected', () => console.info('disconnected mongodb')); // routing specific pages: app.get('/', function(req, res){ res.send('hello world'); }); app.get('/api/genres', function(req , res){ genre.getgenres(function(err, genres){ if(err){ throw err; } res.json(genres); }) }); app.post('/api/genres', function(req , res){ var genre = req.body; genre.addgenre(genre, function(err, genre){ if(err){ throw err; } res.json(genre); }) }); app.get('/api/books', function(req , res){ book.getbooks(function(err, books){ if(err){ throw err; } res.json(books); }) }); app.get('/api/books/:_id', function(req , res){ book.getbookbyid(req.params._id, function(err, book){ if(err){ throw err; } res.json(book); }) }); //specify listening port app.listen(3666); //display url on termianl console.log('server running on http://localhost:3666');
genres
var mongoose = require('mongoose'); var genreschema = mongoose.schema({ name:{ type: string, requires: true }, create_date:{ type: date, default: date.now } }); var genre = module.exports = mongoose.model('genre', genreschema); module.exports.getgenres = function(callback, limit){ genre.find(callback).limit(limit); } //add genre module.exports.addgenre = function(genre, callback){ genre.create(callback); }
i post using postman app , once press post receive nothing , nothing added database
postman procedure
and database before , after post procedure remain same
try instead:
module.exports.addgenre = function(genre, callback){ genre.create(genre, callback); // genre object added, { name: "name" } example }
Comments
Post a Comment