Mongoose is updating wrong object in mongodb

Asked

Viewed 383 times

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

Usando o Robo 3T

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: inserir a descrição da imagem aqui

1 answer

1

I don’t know if you have any server configuration file, but one of the things that might be happening is the express doesn’t understand req.body, in case you haven’t put another place, add that below express require;

const express = require('express')
express.use(express.json())
const router = express.Router()

and checks if req.body is bringing the data from the front.

tries to change doc.save() to doc.update();

  • 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 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

  • 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)

  • Got it, try changing doc.save() to doc.update() since you just want to update the schema and not create another one.

  • Hmmmm, okay I’ll try

  • 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.

  • The Fabio, type after creating the registration in Mongo I have to update the model in Mongoose, or it does it alone?

  • 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

  • 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

  • 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.

  • I’ll update the title of this one

  • Blz Eduardo, I hope I helped man, hug

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.