MongoDB. Is there a way to relate collections?

-1

I am working with a CRUD app with the MEAN stack to keep track of patients, I have a requirement to add a medical history to the patient with the particularity that when you delete a patient, only the patient is deleted, and your medical history remain in the BD. The only thing that has occurred to me is to create another schema of historia.js and make the reference in the schema pacientes.js

Annex part of the code of both

historia.js

var mongoose = require("mongoose");
var Schema = mongoose.Schema;
var Paciente = mongoose.model("Paciente");

var historia_schema = new Schema({

    descripcion: {type: String, required: true},
    paciente: {type: Schema.Types.ObjectId, ref: "Paciente", required: true}

});

module.exports = mongoose.model("Historia", historia_schema);

Patient.js

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


//Modelo del paciente
var paciente_schema = new Schema({

    nombre: {type: String, required: true},
    estado: {type: String, required: true, default: "En espera"},
    fecha: {type: String, required: true},
    edad: {type: String, required: true},
    sexo: {type: String, required: true},
    direccion: {type: String, required: true},
    contacto: {type: String, required: true}

});


//exportando modelo del paciente
module.exports = mongoose.model("Paciente", paciente_schema);

//var dt = dateTime.create();
//var fechapc = dt.format('Y-m-d H:M');
//console.log(fechapc);
//if(req.body.fecha === fechapc){
//  Paciente.estado = "Atendido";
//}

app.js

//importando paquetes y módulos necesarios
var express = require("express");
var bodyParser = require("body-parser");
var mongoose = require("mongoose");
var Paciente = require("./models/pacientes");
var dateTime = require("node-datetime");
var Historia = require("./models/historia");





//asignando express a app para inicializarlo
var app = express();

//conexión a mongoDB, pasamos el servidor(localhost), y el nombre de la BDD(pacientes)
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 })); //facilita la lectura de los parámetros de una petición
app.use(express.static("client")); //servido de archivos estáticos


//obteniendo los pacientes
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);
        }
//Paciente.findOneAndUpdate({_id: req.params.id, fecha: {$lt: Date()}}, {$set: {estado: 'Atendido'}});
    });

});


//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.findOneAndUpdate({_id: req.params.id, fecha: {$lt: Date()}}, {$set: {estado: 'Atendido'}}, function(err, paciente){
        if(err){
            res.send("Ocurrió error obteniendo el paciente deseado");
        }else{
            res.json(paciente);
        }

    });
});


//agregando pacientes
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);
        }

    });
});



//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);
        }

    });

/* === SOL === */
//  req.body.fecha = new Date(req.body.fecha);
//  console.log("=== "+req.body.fecha);
//  Paciente.findOneAndUpdate({_id: req.params.id, fecha: {$lt: Date()}}, {$set: {estado: 'Atendido'}});

});


//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);
        }

    });
});

//agregando historia
app.post("/app/pacientes/:id/addhistoria", function(req, res){
    Historia.create(req.body, function(err, historias){
        if(err){
            res.send("Error al agregar paciente");
        }else{
            res.json(historias);
        }
    });
});


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

The stories are stored in another collection but when I do the ref: "Paciente in historia.js, it does not save anything. Thanks for your help.

    
asked by Ed. 25.08.2017 в 23:47
source

3 answers

0

What you could do is put an extra field to know if it has to be shown in your system that you are doing, this if not bad memory is called logical deletion.

An example would be to add a field called deletion_date, when you delete a patient, put a date to know what day you "got" from the system and filter based on that field.

    
answered by 26.08.2017 в 06:59
0

To relate your collections you should have the history as an attribute of the patient collection:

//Modelo del paciente
var paciente_schema = new Schema({
    nombre: {type: String, required: true},
    estado: {type: String, required: true, default: "En espera"},
    fecha: {type: String, required: true},
    edad: {type: String, required: true},
    sexo: {type: String, required: true},
    direccion: {type: String, required: true},
    contacto: {type: String, required: true}
    historial: {type: Schema.Types.ObjectId, ref: "historiales", required: true}
});

var historia_schema = new Schema({
    descripcion: {type: String, required: true}
    fecha_registro: {type: Date, default: Date.now() } // quizá quieras esto y otros datos importantes ...    
});

Notice that I put the names of the collections in the plural, as I remember, mongoose you create the collections that way even if you put them in the singular, it has only happened to me to add an "s" at the end. So you have it in mind.

If you define it in this way, your queries could be something like:

Paciente.
  find().
  populate('historiales').
  exec(function (err, pacientes) {
    if (err) return handleError(err);
    console.log(pacientes);
    // imprime un array de pacientes con sus historiales
  });

On the other hand, it may be good that when you delete a patient you do it with logical deletion as they say in the other answer, because if the patient registers again, you have their records. This is done by placing a new attribute on the patient model where you indicate whether it is active or not. This unless the requirements say so because patients die and it is not necessary to register them again ...

    
answered by 28.08.2017 в 17:35
0

Although in MongoDB relationships can also be considered if collections are thought of as tables, the reality is that in order to establish relationships, it is better to stay on relational bases.
If you are going to pose a diagram from 1 to N, that is, a patient has many stories, that is, the story is made up of other minor elements, the best idea is to pose an embedded document, like this example JSON:

{
    "_id" : ObjectId(""),
    "nombre" : "Nombre del Paciente",
    "estado" : "Tipo de Estado",
    "fechaAlta" : ISODate("1995-01-22T00:27:00.057Z"),
    "fechaNacimiento" : ISODate("2018-08-07T00:27:00.057Z"),
    "direccion" : "Direccion",
    "contacto" : "Contacto",
    "eliminado" : parseInt(0),
    "historia" : [ 
        {
            "_id" : ObjectId(),
            "descripcion" : "Descripcion de la historia",
            "fechaConsulta" : ISODate("2018-08-07T00:31:29.648Z")
        }, 
        {
            "_id" : ObjectId(),
            "descripcion" : "Descripcion de la historia",
            "fechaConsulta" : ISODate("2018-08-07T00:31:29.648Z")
        }
    ]
}

And control a deleted variable, that when conducting a patient search, only return those that have the status in 1, that is, apply a business rule.

    
answered by 08.08.2018 в 14:18