我想檢查串列中的專案。如果專案存在,我將更新它或在專案不存在時創建。我下面的代碼適用于單個專案,但使用串列時會出錯。
我的模特
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)
我該如何修復它或有什么方法可以解決我的問題? 我真的很感謝你的幫助,祝你有美好的一天!
uj5u.com熱心網友回復:
不能res.send()多次呼叫。為避免這種情況,將所有更新包裝到 a 中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))
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/321282.html
標籤:javascript 节点.js MongoDB 猫鼬
