首页 > 解决方案 > 猫鼬:如果存在多个对象,如何更新它,如果它不退出,如何创建?

问题描述

我想检查列表中的项目。如果项目存在,我将更新它或创建如果项目不存在。我下面的代码适用于单个项目,但使用列表时会出错。

我的模特

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)

以及我如何使用它

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

和我得到的错误

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

我该如何解决它或有什么方法可以解决我的问题? 我真的很感谢你的帮助,祝你有美好的一天!

标签: javascriptnode.jsmongodbmongoose

解决方案


您不能res.send()多次调用。为了避免这种情况,将所有更新包装到 aPromise.all()中以等待所有更新完成并且只在最后发送一次结果。

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

推荐阅读