Relationships in mongoose with personalized id

0

I have 2 models that I want to relate to be able to make queries in mongoose.

Users Model

import mongoose from 'mongoose'
const Schema = mongoose.Schema

let csvuaSchema = new Schema({
 codigo: { type: 'String' },
 georeferencia: { type: 'String'},
 tipo: { type: 'String' }
})

let csvua = mongoose.model('csvua', csvuaSchema)

export default csvua

Readings Model

import mongoose from 'mongoose'
const Schema = mongoose.Schema

let csvlecSchema = new Schema({
 codigo: { type: 'String', ref: 'csvuas'},
 fecha_lectura: { type: 'Date' },
 lectura: { type: 'Number' }
})

let csvlec = mongoose.model('csvlec', csvlecSchema)

export default csvlec

The information is obtained from csv files and I upload it to mongodb in a massive way and I need to be able to consult all the readings of a user through the user code. Can I use the user code to make a query that gets all the readings from the user or is it necessary to use the user's _id? I do not want to use the _id that generates mongoose for the user because when trying to add readings in bulk it would have to consult the _id of the user with its code and I think it is not ideal for performance.

    
asked by Edwin V 09.12.2018 в 23:32
source

2 answers

2

You can change the ObjectId when you insert the document again, for example, user.insert({_id:"pepe",apellido:"Lopez"}) , in this way you would insert the ObjectId that you need but keep in mind that it should be unique.

Now, according to my experience, the best thing that has happened to me has been to use the ObjectId created by MongoDB when inserting the document since it ensures that it is unique and, in addition, the searches that you have related by its own ObjectId are more effective and fast.

If your problem is the relation of collections, you can use the process 'aggregate ()' with the '$ lookup' stage of MongoDB if you have available from version 3.2 or higher of MongoDB, where you can relate collections from the field that you need and return the data already related. I'll give you an example so you can get an idea:

csvuaSchema.aggregate([
    {
        $match: { //Etapa para buscar (símil al find)
            codigo: '1234' //Campo de búsqueda
        }
    },
    {
        $lookup: { 
            from: 'csvlec', //Nombre de la colecccion a relacionar
            localField: 'codigo', //Nombre del campo de la coleccion actual
            foreignField: 'codigo', //Nombre del campo de la coleccion a relacionar
            as: 'lecturas' //Nombre del campo donde se insertara todos los documentos relacionados
        }
    },
    {
        $project: {
            _id: 1,
            codigo: 1,
            georeferencia: 1,
            lecturas: 1 //Devolverà un Array de documentos que tiene el usuario '1234'
        }
    }
])

Exit:

    [{
        _id: ObjectId("5bf6f3d25f2ea179733c1315")
        codigo: '1234',
        georeferencia: 'tugeoreferencia',
        tipo: 'tutipo',
        lecturas: [
            {
                codigo: '1234',
                fecha_lectura: 'fecha1',
                lectura: 'lectura1'
            },
            {
                codigo: '1234',
                fecha_lectura: 'fecha2',
                lectura: 'fecha2'
            }
        ]
    }]

More info: link

About the performance of the searches, I recommend that you include index in the collections that will help you a lot in the searches and more if you have to extract many documents. ( link )

    
answered by 10.12.2018 / 21:43
source
0

I can not prove it right now, but in theory if you could do it, you should make sure that the identifiers were unique (use index and unique in the user)

    
answered by 10.12.2018 в 12:55