I'm trying to push an array of objects and save changes using in-memory objects instead of $push command but it only accepts a single ObjectId. Is there a way of doing it? My goal is efficiency as I've got the database object in memory already.
The Schema:
const mongoose = require("mongoose");
const planejamentoSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "users",
},
dia: Date,
receitas: [
{
_id: {
type: mongoose.Schema.Types.ObjectId,
ref: "receitas",
},
nome: String,
refeicao: String,
},
],
});
const Planejamentos = mongoose.model("planejamentos", planejamentoSchema);
module.exports = Planejamentos;
The route with $push
router.post("/", tokenValidation.checkToken, (req, res) => {
let user = req.body.user;
let dia = req.body.dia;
const query = { user, dia };
Planejamentos.findOne(query).exec((err, result) => {
// AS YOU CAN SEE, I'VE GOT TO QUERY IT AGAIN
// INSTEAD OF JUST result.receitas.push(req.body.receitas)
Planejamentos.updateMany(
query,
{
$push: {
receitas: { $each: req.body.receitas },
},
},
(err, result) => {
res.send(
`Planejamento para ${query.user} em ${query.dia} atualizado com sucesso`
);
}
);
});
});
$pushis still your best shot as it ensures an atomic update to yourPlanejamentosdocument. If you were to update the array in memory, you would still have to execute a.save()on the model to ensure that the update gets saved to the database. So either way, you still have to make a trip down to the database..findOnequery, you can make the update query faster by callingupdatedirectly on the result of the.findOne, i.e something likeresult.update({ $push: { ... } })as opposed to the.updateManyyou currently have.