mongodb 发布房间时在数据库中获取空字段

wko9yo5t  于 2023-01-04  发布在  Go
关注(0)|答案(1)|浏览(89)

我已经发布了一个房间,房间被张贴在数据库中完美地改变预订状态为真。但其余的添加字段,如客户名称,日期,开始时间和结束时间字段被添加,但这些字段在数据库中为空。(注:使用mongodb)。

router.post('/booking',async(req,res)=>{
  await client.connect()
  try{
    data={
      customerName:"",
      date:"", 
      startTime:"",
      endTime:"",
      room_ID:""
    }
    const db =await client.db(dbName)
    let requests = await db.collection('RoomCreation').find({room_ID:req.body.room_ID}).toArray();//Getting the data
    console.log(requests)
    
    if(requests[0].Booked_Status===true){
      res.send({
        statusCode:400,
        message:"Room is full"
      })
    }
    else{
      let postroom=await db.collection('roombook').insertOne(req.body);//In another collection making entries
      let room=await db.collection("RoomCreation").findOneAndUpdate({room_ID:req.body.room_ID},{$set:{Booked_Status:true,customerName:req.body.customerName,date:req.body.date,startTime:req.body.startTime,endTime:req.body.endTime}}) //Updating the fields in main collection
      console.log(room)
      res.send({
        statusCode:200,
        data:room,
        data:postroom,
        message:"Room is created for you succesfully"
      })
    } 
   
  }
  catch(error){
    console.log(error)
    res.send({
      statusCode:500,
      message:"Internal Server Error",
      booked:false,
      error
    })
  }
  finally{
    client.close()
  }        
})

输入/输出:

{
"Customer_Name":"kranthi",
"Date":"03-01-2022",
"Start_Time":"19:00",
"End_Time":"23:00",
"room_ID":"201"
}

MongoDB中的O/P:

_id:6340d27d827a4536d5b0a952
room_ID:"201"
Seats_Available:5
Amenities
Array
Price:"8000"
Booked_Status:true
customerName:null
date:null
endTime:null
startTime:null
xwmevbvl

xwmevbvl1#

正如@Joe建议的那样,你应该这样写:

let room = await db.collection('RoomCreation').findOneAndUpdate(
  { room_ID: req.body.room_ID },
  {
    $set: {
      Booked_Status: true,
      customerName: req.body.Customer_Name,
      date: req.body.Date,
      startTime: req.body.Start_Time,
      endTime: req.body.End_Time,
    },
  },{
    returnNewDocument: true
  }
);

相关问题