简体   繁体   English

猫鼬推入阵列不起作用

[英]mongoose push into array not working

I am making a Library Management app with Nodejs at the backend and MongoDB as the database. 我正在使用后端的Nodejs和MongoDB作为数据库来制作Library Management应用程序。 It is a simple express server and uses mongoose library. 这是一个简单的快递服务器,使用猫鼬库。 The client who has to issue a book sends a POST request and its record is added to the database. 必须发行书籍的客户端发送POST请求,并将其记录添加到数据库中。 Here is the model of my Logs: 这是我的日志的模型:

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

Now when the POST request is received, I try to change the "status" of book from "Available" to "Issued", and add the record of the customer in "details" field. 现在,当收到POST请求时,我尝试将书籍的“状态”从“可用”更改为“已发行”,并在“详细信息”字段中添加客户的记录。 Here is the code: 这是代码:

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 !"
    });
  });
});  

The server crashes when i send this POST request. 当我发送此POST请求时,服务器崩溃。 On checking the database, i found that the "status" field successfully changes from "Available" to "Issued", but no record was inserted in "details". 在检查数据库时,我发现“状态”字段已成功从“可用”更改为“已发行”,但未在“详细信息”中插入任何记录。 Is there something wrong with my query? 我的查询有问题吗? Please suggest corrections to my code. 请提出对我的代码的更正。
This is the snippet of error while crashing: 这是崩溃时的错误摘要:

Error in Terminal can be seen below: 终端错误如下所示:

在此处输入图片说明

Change this code 更改此代码


Logs.findOneAndUpdate({bookid: req.body.bookid}, {$set: {status:"Issued"}}, {$push: {details:detail}}, {upsert: true}, function(err,doc)

To this 对此


Logs.findOneAndUpdate({bookid: req.body.bookid}, {$set: {status:"Issued"}}, {$push: {details:detail}}, {upsert: true}).then((result) => {
  console.log(result)
}.catch((error) => {
  console.log(error)
}

Please tell me what the console.log(error) will return you and according to that error message, I am able to give you a final answer. 请告诉我console.log(error)将返回您什么,并且根据该错误消息,我能够为您提供最终答案。

Update 更新资料


You might try the following code block. 您可以尝试以下代码块。 This code will look for a Log with the Id you'll provide in the request.body and with a status of Available. 此代码将查找具有您将在request.body中提供的ID且状态为Available的日志。 If this query finds the Log it will send it back in the response. 如果此查询找到日志,它将在响应中将其发送回去。 If not, it'll throw an error that it didn't find it. 如果没有,它将抛出一个找不到的错误。

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

The error is probably because you are not updating the details field correctly. 该错误可能是因为您没有正确更新详细信息字段。 As I can see in your schema, you have defined details to be [] but you are updating it with an object {} . 正如我在您的模式中看到的那样,您已将details定义为[]但正在使用对象{}对其进行更新。 You have to fix that. 您必须解决该问题。 But also I think you can make the script better. 但我也认为您可以使脚本更好。 The statement: 该声明:

Logs.findOneAndUpdate({bookid: req.body.bookid}, {$set: {status:"Issued"}}, {$push: {details:detail}}, {upsert: true}, function(err,doc) {

seems redundant. 似乎多余。 You already have the doc you need to update in: 您已经有了需要更新的文档:

Logs.findOne({bookid: req.body.bookid}).then((doc) => {

After you get this doc , just modify whatever you want akin to a javascript object and do doc.save 获取此doc ,只需修改您想要的类似于javascript对象的内容,然后执行doc.save

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM