-3

I am doing a project where my website showcase event information and the date like example 5sep. However i want to auto update a field in which set waiting to attended, when current date is same or already exceed the setted date. I'm using mongoDB, nodeJs, mongoose.

Schema model

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var dateTime = require("node-datetime");

var paciente_schema = new Schema({

nombre: {type: String, required: true},
estado: {type: String, required: true},
fecha: {type: Date, required: true},
edad: {type: String, required: true},
sexo: {type: String, required: true},
direccion: {type: String, required: true},
contacto: {type: String, required: true}

});
module.exports = mongoose.model("Paciente", paciente_schema);

app.js

    var express = require("express");
    var bodyParser = require("body-parser");
    var mongoose = require("mongoose");
    var Paciente = require("./models/pacientes");
    var dateTime = require("node-datetime");


    var app = express();
    mongoose.Promise = global.Promise;
    var mongoDB = mongoose.connect('mongodb://localhost/pacientes', {
    useMongoClient: true
    });


    app.use(bodyParser.json()); //leyendo parámetros de una petición JSON
    app.use(bodyParser.urlencoded({ extended: true }));
    app.use(express.static("client")); //servido de archivos estáticos



    app.get("/app/pacientes", function(req, res){
//find busca todos los datos de la DB
    Paciente.find(function(err, pacientes){
        if(err){
            res.send("Ocurrió error obteniendo los pacientes");
        }else{
            res.send(pacientes);
        }
    });
});


//obteniendo UN paciente
app.get("/app/pacientes/:id", function(req, res){
//método findOne el cual recibe el id del paciente a buscar en la DB
    Paciente.findOne({_id: req.params.id}, function(err, paciente){
        if(err){
            res.send("Ocurrió error obteniendo el paciente deseado");
        }else{
            res.json(paciente);
        }

    });
});



    app.post("/app/pacientes", function(req, res){
//creando paciente con los datos enviados por el user en el cuerpo de la petición
    Paciente.create(req.body, function(err, pacientes){
        if(err){
            res.send("Error al agregar paciente");
        }else{
            res.json(pacientes)
        }

console.log("FECHA USUARIO: " + req.body.fecha); //Mark
console.log(typeof(req.body.fecha));
var fecha2 = fecha2.toDate()
var fecha = new Date();
console.log("FECHA NEW DATE " + fecha);
console.log(typeof(fecha));
if(req.body.fecha === fecha){
    console.log("WWWW");
}


    });
});


//actualizando paciente
app.put("/app/pacientes/:id", function(req, res){
//creamos una variable(actualiza) la cual tomará los atributos a actualizar y se enviará como un query en el método update
    var actualiza = {

        nombre: req.body.nombre,
        estado: req.body.estado,
        fecha: req.body.fecha,
        edad: req.body.edad,
        sexo: req.body.sexo,
        contacto: req.body.contacto

    };
//encontramos un paciente y lo actualizamos, pasamos el query con los atributos actualizados
    Paciente.findOneAndUpdate({_id: req.params.id}, actualiza, function(err, paciente){
        if(err){
            res.send("Ocurrió error actualizando" + err);
        }else{
            res.json(paciente);
        }

    });
});


//borrar paciente
app.delete("/app/pacientes/:id", function(req, res){
//método para encontrar y eliminar un dato en la DB, el _id es el identificador en la DB
    Paciente.findOneAndRemove({_id: req.params.id}, function(err, pacientes){
        if(err){
            res.send("Error al eliminar el paciente");
        }else{
            res.json(pacientes)
        }

    });
});



//app corriendo en puerto 8888
app.listen(8888, function() {
    console.log("App corriendo en 8888");
});

routes.js

//Modulo que engloba los controladores, rutas y demás configuracione
var myApp = angular.module("myApp", ["ngRoute"]);
//Agregamos el módulo ngRoute como una dependencia, hace que la app sea SPA
myApp.config(function($routeProvider){
    //con el módulo ngRoute agregado podemos usar el routeProvider, el cual se usa para configurar diferentes rutas
    //inicio
    $routeProvider
        .when("/", {
            templateUrl: "templates/lista.html",
            controller: "empController"
        })
        //lista de pacientes
        .when("/pacientes", {
            templateUrl: "templates/lista.html",
            controller: "empController"
        })
        //mostrar un paciente en específico
        .when("/pacientes/:id/mostrar", {
            templateUrl: "templates/mostrar.html",
            controller: "empController"

        })
        //crear un paciente
        .when("/pacientes/crear", {
            templateUrl: "templates/crear.html",
            controller: "empController"
        })
        //editar un paciente
        .when("/pacientes/:id/editar", {
            templateUrl: "templates/editar.html",
            controller: "empController"
        });
});

I don't know if I need to post anymore code in here, let me know about it, I'm pretty new in it. Sorry I just wanna know how can I change the status (estado) which takes 2 values either Waiting or Attended through a radio form, I wanna know how could it be automatically updated to Attended once the current date (fecha) matches the date (fecha) put in by the user.

Ed.
  • 13
  • 6
  • You might want to share a little bit (a lot in fact) more information about your specific case. Sample data, sample queries, a precise question or anything that makes your problem a bit clearer to us. – dnickless Aug 17 '17 at 21:08
  • Update MongoDB field using value of another field That's what I basically wanna do, when current date is "higher" then the put date in the form I want the status to change – Ed. Aug 18 '17 at 14:39
  • I am still not quite sure I understand. Are you perhaps having the same problem as this guy here? https://stackoverflow.com/questions/3974985/update-mongodb-field-using-value-of-another-field – dnickless Aug 18 '17 at 18:01
  • Sort of but not really. What I meant is this:: I have this form, where there're alot of fields, one of them is **status** (which takes 2 values: Waiting and Attended) and one of the others is **date**, all of the data from the form is sent to a mongoDB with mongoose. What I wanna do is, with the date in the DB I wanna find a way that when the current PC date is >= than the date in the DB, the value of the status field changes automatically from waiting to attended. That's all I wanna do, I don't know how to. I hope you understand me now – Ed. Aug 19 '17 at 01:00

1 Answers1

0

This cannot be done using a single standard update command (also see here and here).

You can, however, solve this in two ways:

You first load the existing entity, you update everything in JavaScript and send it to MongoDB:

Paciente.findOne({_id: req.params.id}).exec(function (err, p) {
    p.nombre = req.body.nombre;
    p.estado = req.body.estado;
    p.fecha = req.body.fecha;
    p.edad = req.body.edad;
    p.sexo = req.body.sexo;
    p.contacto = req.body.contacto;

    if (p.fecha < Date()) {
        p.estado = "attended";                       
    }

    Paciente.save(p);
});

As an alternative, you pretty much keep what you have and then send a second update query with an additional filter like so:

// update your document first
Paciente.findByIdAndUpdate(req.params.id, actualiza);

// update estado if fecha is in the past
Paciente.findOneAndUpdate({_id: req.params.id, fecha: {$lt: Date()}}, {$set: {estado: 'attended'}});

I would personally recommend you go for the second approach.

dnickless
  • 10,733
  • 1
  • 19
  • 34
  • Thanks for you answer sir, will definitely try that! What I understood is I place the `Paciente.findOneAndUpdate({_id: req.params.id, fecha: {$lt: Date()}}, {$set: {estado: 'attended'}});` Insine my update function – Ed. Aug 21 '17 at 13:29
  • This works but not as expected. It should be like listen all the time to the server so when I print out the list of patients, the status(estado) field should've been updated automatically, without going to edition the patient – Ed. Aug 21 '17 at 15:55
  • That cannot be done using MongoDB. You can, of course, use projections to retrieve a different value for `estado` from the database, no matter what's actually stored. In this case, I would suggest you do not even store `estado` because it seems more like a calculated value than something that needs to be stored...? – dnickless Aug 21 '17 at 16:03
  • That's what I thought. Still thanks for helping me! That's not exactly the solution but it does works in a different way that expected – Ed. Aug 21 '17 at 19:49