简体   繁体   中英

Web service RESTful with node.js

I have a connection between mongodb and node.js , but when I test this methods , always give me null or documents that there aren't in the DB. What am I doing wrong?

index.js(main file) Where I call the routers

 var express = require("express"),
 app = express(),
 bodyPaser = require("body-parser"),
 methodOverride  = require("method-override"),
 mongoose = require('mongoose');
 var port = 3000;
 mongoose.connect('mongodb://localhost:27017/task',
 function(err,res){
 if(err){return console.log(`Error al Conectar a la BD stablish ${err}`)};
 console.log('Conexión a la BD stablish');},{ useMongoClient: true });
 app.use(bodyPaser.urlencoded({ extended : false}));
 app.use(bodyPaser.json({ type: 'application/json' }));
 app.use(methodOverride());
 var models = require('./models/task')(app, mongoose);
 var TaskListCtrl = require('./controller/taskListController');
 var router = express.Router();
 router.get('/', function(req, res) {
 res.send("Hello world!");
 });
 app.use(router);
 var task = express.Router();
 task.route('/task')
 .get(TaskListCtrl.findAllTasks)
 .post(TaskListCtrl.addTask);
 task.route('/task/:id')
 .get(TaskListCtrl.findById)
 .put(TaskListCtrl.updateTask)
 .delete(TaskListCtrl.deleteTask);
 app.use('/api', task);
 app.listen(3000, function() {
 console.log("Node server running on http://localhost:3000");
 });

package.json

{
    "name": "restnodetask",
    "version": "1.0.0",
    "description": "Proyecto de API RESTful con Node.js y Express",
    "main": "index.js",
    "scripts": {
                 "start": "nodemon index.js",
                 "test": "echo \"Error: no test specified\" && exit 1"
                },
    "author": "Jean Carlo Flores",
    "license": "MIT",
    "dependencies": {
    "body-parser": "^1.17.2",
    "express": "^4.15.3",
    "method-override": "^2.3.9",
    "mongodb": "^2.2.30",
    "mongoose": "^4.10.8"
    },
    "devDependencies": {
    "nodemon": "^1.11.0"
    }
    }

controller/taskLisController (where I am asking for response)

var mongoose = require('mongoose');
var Task = mongoose.model('Task');
exports.findAllTasks = function(req, res) {
Task.find(function(err, task) {
if (err) res.send(500,err.message);
console.log('GET /tasks');
res.status(200).jsonp(task);
res.body = task;
});
};  
exports.findById = function(req, res) {
Task.findById(req.params.id, function(err,task) {
if(err) return res.send(500, err.message);
console.log('GET /task/' + req.params.id);
res.status(200).jsonp(task);
});
};
exports.addTask = function(req, res) {
console.log('POST');
console.log(req.body);
var task = new Task({
    objectId : req.body.objectId,
    title : req.body.title,
    remember : req.body.remember,
    date_time : req.body.date_time 
});
task.save(function(err, task) {
    if(err) return res.send(500, err.message);
    res.status(200).jsonp(task);
});
};
exports.updateTask = function(req, res) {
Task.findById(req.params.id, function(err, task) {
    task.objectId   = req.body.objectId;
    task.title    = req.body.title;
    task.remember = req.body.remember;
    task.date_time = req.body.date_time;
    task.save(function(err) {
            if(err) return res.send(500, err.message);
            res.status(200).jsonp(task);
    });
});
};
exports.deleteTask = function(req, res) {
Task.findById(req.params.id, function(err, task) {
    task.remove(function(err) {
        if(err) return res.send(500, err.message);
        res.status(200);
    })
});
};

My Model at mongoDB

exports = module.exports = function(app, mongoose) {
var taskSchema = new mongoose.Schema({
objectId : { type:String} ,
title : { type:String},
remember : { type: Boolean},
date_time : { type:Date}
});
 mongoose.model('Task',taskSchema);
};

First of all, you seem to be new here so please try to edit your question to format the code correctly. Right now your indentation is completely messed up which make it very misleading and impossible to read. Also please try to narrow down your code to show a minimum example that demonstrate your problem, with expected and actual output. It will make it much more likely to get an answer that would solve your problem.

I have a connection between mongodb and node.js , but when I test this methods , always give me null or documents that there aren't in the DB. [emphasis added]

I highly doubt that you really get any documents that are not in the database. Maybe you're not connecting to the right database. Or maybe those documents are in the database even though you think they are not. Either way I haven't heard about getting documents that are not in the database. Do they resemble in any way other documents that are (or used to be) in the database? If so then I would assume that they are in the database and you need to investigate why.

Did you try connecting with the database with a command line console to verify what is and what is not in the database? You certainly should start from that.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM