Home > Software design >  mongoose : how to update mutiple object if it exist or create if it doesn't exit?
mongoose : how to update mutiple object if it exist or create if it doesn't exit?

Time:10-12

i want to check item in a list. if item exist i will update it or create if item doesn't exits. my code below work with single item, but with a list it get a error.

my Model

const mongoose = require('mongoose')
const Schema = mongoose.Schema
const Personal = new Schema({
    personalName: { type: String, default: "" },
    listUserId: { type: [String] },
    createAt: { type: Date, default: Date.now }
}, {collection:'personals', versionKey: false })

module.exports = mongoose.model('Personal', Personal)

and how i use it

app.put("/update_personal", (req, res, next) => {
    for (var i in req.body.personalName) {
        var item = req.body.personalName[i]
        Personal.find({ personalName: item })
            .then(result => {
                if (result.length > 0) {
                    Personal.updateOne(
                        { personalName: item },
                        { $push: { listUserId: req.body.userId } },
                        {
                            returnNewDocument: true,
                            new: true,
                            strict: false
                        })
                        .then(result => res.send(result))
                        .catch(err => res.send(err))
                } else {
                    const list = []
                    list.push(req.body.userId)
                    const personal = new Personal({ personalName: item, listUserId: list })
                    personal.save()
                        .then(result => {
                            res.send(JSON.stringify(result))
                            console.log(req.body)
                        })
                        .catch(err => res.send(err))
                }
            })
            .catch(err => res.send(err))
    }
})

and the error i got

(node:10276) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
    at ServerResponse.setHeader (_http_outgoing.js:561:11)
    at ServerResponse.header (C:\Workspace\Nodejs\Snowy\node_modules\express\lib\response.js:771:10)
    at ServerResponse.send (C:\Workspace\Nodejs\Snowy\node_modules\express\lib\response.js:170:12)
    at ServerResponse.json (C:\Workspace\Nodejs\Snowy\node_modules\express\lib\response.js:267:15)
    at ServerResponse.send (C:\Workspace\Nodejs\Snowy\node_modules\express\lib\response.js:158:21)
    at C:\Workspace\Nodejs\Snowy\server.js:71:43
    at processTicksAndRejections (internal/process/task_queues.js:95:5)
(node:10276) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 7)

how can i fix it or have any way to solve my problem? I really appreciate your help and have a nice day!

CodePudding user response:

You cannot call res.send() multiple times. To avoid this wrap all updates into a Promise.all() to wait for all updates to finish and only send the result at the end once.

app.put("/update_personal", (req, res, next) => {
  Promise.all(req.body.personalName.map(item => {
    return Personal.find({ personalName: item }).then(result => {
      /* ... */

      return personal.save()
        .then(result => JSON.stringify(result))                        
    })
  }))
    .then(result => res.send(result))
    .catch(err => res.send(err))  
})
  • Related