猫鼬 :如果存在,如何更新多个对象,如果它不退出,如何创建?



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

我的型号

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:WorkspaceNodejsSnowynode_modulesexpresslibresponse.js:771:10)
at ServerResponse.send (C:WorkspaceNodejsSnowynode_modulesexpresslibresponse.js:170:12)
at ServerResponse.json (C:WorkspaceNodejsSnowynode_modulesexpresslibresponse.js:267:15)
at ServerResponse.send (C:WorkspaceNodejsSnowynode_modulesexpresslibresponse.js:158:21)
at C:WorkspaceNodejsSnowyserver.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)

我该如何解决问题?我真的很感谢你的帮助,祝你今天愉快

不能多次调用res.send()。为了避免这种情况,将所有更新打包到Promise.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))  
})

最新更新