1
I have a problem saving the data in mongodb.
Context
I have an express api that listens to requests to save the data to the mongodb an application sends. This data is related to APP page views, clicks, etc.
add.js
This is the file responsible for updating the field dataEvent: {type: Array, require: true}
in the Mongoose model. On this route I look for the id that is sent by the application and push this array.
require('../models/Event')
const express = require('express')
const router = express.Router()
const mongoose = require('mongoose')
const Event = mongoose.model("event")
const { validateToken } = require('../helpers/validateToken')
const {Console} = require('../providers/console-provider')
const {response} = require('../helpers/response-helper')
router.put('/', (req, res) => {
let id = req.body.id
data = req.body.body
console.log(data)
if(id != undefined & data != undefined){
Event.findOne({_id: id}).then(async (doc)=>{
await doc.dataEvent.push(data)
doc.save().then(async (s)=>{
console.log("Add com sucesso")
console.log(s)
await response(200, "Evento adicionado com sucesso!", res)
}).catch(()=>{
res.status(500)
res.send({error: true, info: "Não foi possível adicionar o evento!"})
})
}).catch((err)=>{
console.log(err)
res.status(500)
res.send({error: true, info: "Não foi possível adicionar o evento!"})
})
}else{
console.log("Dados da requisição inválidos!")
res.status(500)
res.send({error: true, info: "Dados inválidos"})
}
})
module.exports = router
Console
In the console this result is displayed (it has some confidential data, but the dataEvent is displayed, with the two records):
Add com sucesso
{ dataEvent:
[ { type: 'view', page: 'login-page' },
{ type: 'click', page: 'doctor-list' } ],
_id: 5dc030cba1752e1b08847884
The problem
The problem in all this is that in mongodb the record that is pushed is not saved! It should have the record added in the file path add.js
server.js
This is the server file
require('dotenv/config')
const {
express,
http,
providers: {
consoleProvider: {
Console
}
},
routes: {
init,
update,
add
},
mongoose,
bodyParser,
cors,
verifyToken: {
validateToken
}
} = require('./import')
const app = express()
const c = Console
if (process.env.ENV == "PROD") {
bd_host = process.env.BD_PROD
} else if (process.env.ENV == "TEST") {
bd_host = process.env.BD_TEST
} else {
bd_host = process.env.BD_DEV
}
app.use(cors())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
mongoose.connect(bd_host, { useNewUrlParser: true, useUnifiedTopology: true }
.then((success) => { Console("Banco de dados conectado!") })
.catch((error) => { Console("Erro ao se conectar com a base de dados!") })
app.use('/init', validateToken, init)
app.use('/add', validateToken, add)
app.use('/update', validateToken, update)
app.use((err, req, res, next) => {
console.log(err)
res.status(500)
res.json({ error: true, info: "Erro interno no servidor" })
})
app.listen(
process.env.PORT,
() => {
Console("Servidor rodando na porta: " + process.env.PORT)
}
)
Situation found
When the app sends a request to the route /init
it generates an id where it is stored on the device. But when the request is made on the route /add
It updates a previous id. I’ll show in the photo:
I’m running this on server.js. which is the server file that’s listening to the port. The data comes all right, because Mongoose adds the record that comes from the application. However in the database it does not save!
– eduardo meurer
Eduardo speaks a curiosity, you are doing the require('./models/Event') and then const Event = Mongoose.model('Event'), because in your model you no longer return a new Mongoose.model('Event', Eventschema)? you would take less risk missing the model’s name
– Fabio Jr
I have a model that I call Mongoose and Schema, so I do the new Event in this model and I call Mongoose.model('Event',Eventschema)
– eduardo meurer
Got it, try changing doc.save() to doc.update() since you just want to update the schema and not create another one.
– Fabio Jr
Hmmmm, okay I’ll try
– eduardo meurer
The same thing happened, instead of adding it to the dataEvent array of the object created by the /init route it added to the previous object.
– eduardo meurer
The Fabio, type after creating the registration in Mongo I have to update the model in Mongoose, or it does it alone?
– eduardo meurer
What do you mean update the model in Mongoose? what you need to do is send the id of the record that you want to update, probably in Event.findOne({_id: id}) probably puts the past id wrong
– Fabio Jr
The id that comes from the API is the same that is generated by the /init route. I don’t know why it’s picking up the previous one
– eduardo meurer
Well, maybe you should open another question by passing the current scenario, I think it would be easier for the guys to help since the problem now is another kkkk.
– Fabio Jr
I’ll update the title of this one
– eduardo meurer
Blz Eduardo, I hope I helped man, hug
– Fabio Jr