0

I'm trying manipulate a JSON that wasn't created by me, only uploaded to mongo. In NodeJs I'm trying:

app.get('/municipios', async (req, res) => {
  let cidadeSchema = new Schema({}, { strict: false })
  let cidades = mongoose.model('municipios', cidadeSchema)
  let cidade = cidades.findOne({name: 'Rio Grande'})
  // console.log(cidade)
  res.send(CircularJSON.stringify(cidade))
})

but when the JSON is sent, it send only the structure of request to mongo, and if I try once, I receive a message: (node:24536) UnhandledPromiseRejectionWarning: OverwriteModelError: Cannot overwrite municipios model once compiled.

Vinícius
  • 35
  • 6

2 Answers2

0

As you are writing the query inside an async method, so you need to await the result of the findOne Query. Below is the snippet of the answer

app.get('/municipios', async (req, res) => {
  let cidadeSchema = new Schema({}, { strict: false })
  let cidades = mongoose.model('municipios', cidadeSchema)
  let cidade = await cidades.findOne({name: 'Rio Grande'})
  // convert the dataset into object
  cidade = cidade.toObject();
  res.send(cidade)
})

After the await, you will get the model data, which you can convert into an object.

NARGIS PARWEEN
  • 1,489
  • 3
  • 16
  • 26
0

The submitted await answer notices one issue, and you need to fix that also, but it doesn't answer your original issue of OverwriteModelError.

I think you are defining your model schema twice.

The accepted answer in This post has a decent explanation of defining your models separately from your other code and it should help you in your issue

Aprona
  • 63
  • 7