Relationship between documents - Mongodb

Asked

Viewed 624 times

1

I have the following model:

  • A schema called suspects, which holds information of suspicious persons.
  • And 3 other so-called alerts, criminal actions and risk events.

These 3 other schemas, must have the suspects' data, for example, the same suspect may appear in the 3 cases. That is, if it were a relational comic book it would be a relationship of n:n (1 or more suspects for 1 or more cases).

Using nonrelational BD (Mongodb), what is the best practice for creating these schemas? I will demonstrate how I did it:

Schema suspects:

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)

Alerts Schema:

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 the other two schemas, the risky events and criminal actions, but these are similar to the alerts.

What I did to link the suspects to alerts is correct?

1 answer

1

In fact the correct thing would be to use the mongoose.Schema.Types.ObjectId, because there at the time of a find({}) you can use the populate to retrieve the information from the other scheme. 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)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.