Relationship between documents - MONGODB

2

I have the following template: A schema called suspects, which has information from suspects. And other 3 so-called alerts, criminal actions and risky events. These 3 other schemas, should have the data of suspects, for example, the same suspect may appear in all 3 cases. That is, if it were a relational DB it would be a relation of n: n (1 or more suspect for 1 or more cases).

Using non-relational DB (mongo), what is the best practice for creating these schemas? I'll demonstrate how I did it:

Suspicions Schema. I created a different file to leave separated by directories.

const restful = require('node-restful')
const mongoose = restful.mongoose

const suspeitosSchema = new mongoose.Schema({
  nome: { type: String, required: true }
})

module.exports = restful.model('suspeitos', suspeitosSchema)

Schema Alerts:

const restful = require('node-restful')
const mongoose = restful.mongoose
const suspeitos = require('./suspeitos') //posso acessar um schema que está em outro arquivo desta forma?

const alertasSchema = new mongoose.Schema({
  name: { type: String, required: true },
  suspeitos: [suspeitosSchema]  //<-- Isso esta certo?  
})

module.exports = restful.model('alertas', alertasSchema)

There are still two other schemas, risk events and criminal actions, but these are similar to alerts.

What did I do to link suspects with alerts correct?

    
asked by anonymous 26.10.2017 / 15:47

1 answer

1

Actually the correct thing would be to use mongoose.Schema.Types.ObjectId , because then at the time of find({}) you can use populate to fetch information from the other schema. It would look like this.

const restful = require('node-restful')
const mongoose = restful.mongoose

const alertasSchema = new mongoose.Schema({
    name: { type: String, required: true },
    suspeitos: [{
        type: mongoose.Schema.Types.ObjectId,
        ref: 'suspeitos'
    }]  
})

module.exports = restful.model('alertas', alertasSchema)
    
29.07.2018 / 08:59