I have 2 models that I want to relate to be able to perform queries in mongoose.
Model Users
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
Model Readings
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
I get the information from csv files and upload it to mongodb in bulk and I need to be able to query all the readings of a user through the user code. Can I use the user code to do a query that gets all the reads from the user or is it necessary to use the _id of the user? I don't want to use the _id that mongoose generates for the user because trying to bulk add reads would have to query the user's _id with your code and I think that's not ideal for performance.
You can change the ObjectId when you insert the document again, for example ,
user.insert({_id:"pepe",apellido:"Lopez"})
this way it would insert the ObjectId you need but note that it would have to be unique.Now, according to my experience, the best thing that has gone for me has been to use the ObjectId that MongoDB creates when inserting the document since it makes sure that it is unique and, in addition, the searches that you have related by its own ObjectId are more effective and faster. .
If your problem is the relationship of collections, you can use the 'aggregate()' process with the '$lookup' stage of MongoDB if you have it available from version 3.2 or higher of MongoDB, where you can relate collections of the field you need and return the related data. I'll give you an example so you can get an idea:
Departure:
More info: https://docs.mongodb.com/manual/reference/operator/aggregation/lookup/index.html
Regarding the search performance, I recommend that you include an index in the collections that will help you a lot in the searches and even more so if you have to extract many documents. ( https://docs.mongodb.com/manual/indexes/index.html )
I can't test it right now, but in theory you could, you should make sure the ids are unique (use index and unique on the user)