0

我正在尝试更新放置在数组中的对象的值。

MongoDB 架构如下:

const ServiceStatus = new Schema({
    CustomerName : { type : String},
    CustomerNumber : {type : String},
    ServiceName : {type : String},
    Details : {type: String},
    Date : {type: String},
    Status : {type : String},
    Comments : {type : String},
    ServiceId : {type: Schema.Types.ObjectId},
    CustomerId : {type: Schema.Types.ObjectId},
    ServiceProvider : {type: Schema.Types.ObjectId},
    message : [{
        sender : {type: String},
        content : {type : String},
        time : {type : String}
    }]
})

并且路线的片段是

router.put('/message/customer/:id',(req, res) => {
    const id=req.params.id;
    Status.findByIdAndUpdate({_id : id}, 
        {
            $push : {
                "message.$.sender": "Customer" ,
                "message.$.content": req.body,
                "message.$.date" : new Date()

            }
        }
    ,{ useFindAndModify: false } )
        .exec((err, status) => res.json(status))
})

当我尝试在邮递员上运行它时,它没有得到更新,但我没有收到任何错误。我想知道我应该如何更改路由器以使其工作。

4

1 回答 1

0

我觉得应该是这样的:

db.ServiceStatus.insertOne(
   {
      CustomerName: "the name",
      message: [{ sender: "Customer", content: "some content", time: new Date() }]
   }
);

db.ServiceStatus.updateOne(
   { CustomerName: "the name" },
   {
      $push: {
         message: { sender: "Another customer", content: "more content", time: new Date() }
      }
   }
)

db.ServiceStatus.find()   

{ 
    "_id" : ObjectId("5fdc4f14d1d3de1f92780a0b"), 
    "CustomerName" : "the name", 
    "message" : [
        {
            "sender" : "Customer", 
            "content" : "some content", 
            "time" : ISODate("2020-12-18T07:41:24.166+0100")
        }, 
        {
            "sender" : "Another customer", 
            "content" : "more content", 
            "time" : ISODate("2020-12-18T07:41:26.328+0100")
        }
    ]
}
于 2020-12-17T14:33:48.243 回答