my goal here is learn how to use models for saving in the desired collection(collection name = year), the problem that i created to solve is the following: Suppose i'm working with data of school/college classes which remain the same (name, location and etc..) but the only variable is the year 2019, 2020 and so on..
I know I can use only one collection and filter by some idyear, but i thought that could be better to separate into a new collection named by the year so I could get something like:
- collection 2018 -> X items
- collection 2019 -> Y items
- collection 2020 -> Z items
I tried the following code:
classModel.js
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const classSchema = new Schema({
name: {type: String, required: true},
info1: {type: String},
iduser: {type: Number}
});
module.exports = mongoose.model('Classes', classSchema);
classController.js
const classModel = require('classModel');
const userModel = require('userModel');
exports.insertClass = async function(req, res){
const user = await userModel.find({
username: req.user
}).limit(1);
await classModel.create({
name: req.name,
info1: req.location,
iduser: user[0].idperson
}, {collection: '999999'}, function(err){
if(err) console.log(err);
res.sendStatus(200);
});
}
The year i am hard coding now, but i plan to be attached to the user session (hence why i use another search). With this code i can manage to insert into the default behavior of the model, in the collection based on the model name but that's not my objective and end up with something like:
- collection classes -> X+Y+Z
I was reading the mongoose doc and found the 'options' and 'set', so I tried to force the collection name in there (like this question) but couldn't do.
I'm stuck in this problem over the weekend so i can't say if I am 'overlooking' at some point or just new into node, if anyone can point me the direction i'd be very glad, i hope the question is clear.