我正在使用后端的Nodejs和MongoDB作为数据库创建一个Library Management应用程序。它是一个简单的快速服务器,使用mongoose库。必须发出书籍的客户发送POST请求,并将其记录添加到数据库中。这是我的日志模型:
var Logs = mongoose.model('Logs', {
bookid: {
type: Number,
required: true,
minlength: 1
},
status: {
type: String,
required: true,
minlength: 1,
trim: true
},
details: [{
issuedby: {
type: String,
trim: true
},
issuedate: {
type: Date,
},
returndate: {
type: Date
}
}]
});
现在收到POST请求时,我尝试将书籍的“状态”从“可用”更改为“已发布”,并在“详细信息”字段中添加客户记录。这是代码:
app.post('/issueBook', (req,res) => {
console.log(req.body);
Logs.findOne({bookid: req.body.bookid}).then((doc) => {
if(doc.status == "Available"){
var detail = {};
detail.issuedby = req.body.issueTo;
detail.issuedate = new Date();
Logs.findOneAndUpdate({bookid: req.body.bookid}, {$set: {status:"Issued"}}, {$push: {details:detail}}, {upsert: true}, function(err,doc) {
if(err) {
console.log("Couldn't issue");
res.status(400).send(err);
} else{
res.send("OK");
}
});
} else{
res.send({
status: "Error",
reason: "Book already issued !"
});
}
}, (e) => {
res.send({
status: "Error",
reason: "Invalid Book ID !"
});
});
});
发送此POST请求时服务器崩溃。在检查数据库时,我发现“status”字段成功地从“Available”更改为“Issued”,但没有在“details”中插入记录。我的查询有问题吗?请建议更正我的代码。 崩溃时这是错误的片段: 终端错误如下所示:
Logs.findOneAndUpdate({bookid: req.body.bookid}, {$set: {status:"Issued"}}, {$push: {details:detail}}, {upsert: true}, function(err,doc)
Logs.findOneAndUpdate({bookid: req.body.bookid}, {$set: {status:"Issued"}}, {$push: {details:detail}}, {upsert: true}).then((result) => {
console.log(result)
}.catch((error) => {
console.log(error)
}
请告诉我console.log(错误)将返回什么,并根据该错误消息,我能够给你一个最终的答案。
Update
您可以尝试以下代码块。此代码将查找带有您将在request.body中提供的ID的日志,状态为Available。如果此查询找到日志,它将在响应中将其发回。如果没有,它会抛出一个它找不到它的错误。
app.post('/api/issueBooking', (request, response) => {
Log.findOneAndUpdate({
bookid: request.body.bookid,
status: "Available"
}, {
$set: {
status: "Issued"
}
}, {
$push: {
"details": {
issueby: "issueByHere",
issuedate: "issueDateHere",
returndate: "returnDateHere"
}
},
{
upsert: true
}).then((log) => {
if (!log) {
return Promise.reject({
status_code: 404,
message: "Log not found."
})
}
response.status(200).send("OK");
}).catch((error) => {
response.status(error.status_code).send(error.message);
})
});
该错误可能是因为您没有正确更新详细信息字段。正如我在您的架构中看到的那样,您已将details
定义为[]
,但您使用对象{}
更新它。你必须解决这个问题。但我认为你可以让脚本变得更好。该声明:
Logs.findOneAndUpdate({bookid: req.body.bookid}, {$set: {status:"Issued"}}, {$push: {details:detail}}, {upsert: true}, function(err,doc) {
似乎多余。您已经拥有需要更新的文档:
Logs.findOne({bookid: req.body.bookid}).then((doc) => {
得到这个doc
后,只需修改你想要的任何类似于javascript对象并做doc.save