首页 > 解决方案 > 如何仅更新 Mongodb 中现有对象的某些键?

问题描述

所以这是我的情况:

在我的 Angular 8 应用程序中,我创建了发票。这是一个发票对象:

{
"_id": {
    "$oid": "5ea9ad58f65d8d49841362bd"
},
"details": [
    {
        "_id": "5ea1eff27a1fcb29c4e7d1b6",
        "Client": "test",
        "km": 88,          
        "Subject": "test",
        "Location": "test",
        "StartTime": "2020-04-27T09:00:00.000Z",
        "EndTime": "2020-04-27T17:00:00.000Z",
        "IsAllDay": false,
        "StartTimezone": null,
        "EndTimezone": null,
        "Description": "oekfokef",
        "RecurrenceRule": "FREQ=DAILY;INTERVAL=1;COUNT=5;",
        "Id": 2,
        "CreatedBy": "bob"
    },
    {
        "_id": "5ea1f36297a9a315bc8ed078",
        "Client": "test",
        "km": 88,      
        "Subject": "ewfwefwe",
        "Location": "fwefwefwefewfwefwef",
        "StartTime": "2020-04-20T09:00:00.000Z",
        "EndTime": "2020-04-20T17:00:00.000Z",
        "IsAllDay": false,
        "StartTimezone": null,
        "EndTimezone": null,
        "Description": "wefwefewfwef",
        "RecurrenceRule": "FREQ=DAILY;INTERVAL=1;COUNT=5;",
        "Id": 3,
        "CreatedBy": "bob"
    },
    {
        "_id": "5ea1f38d97a9a315bc8ed083",
        "Client": "test2",
        "km": 38,
        "Subject": "test",
        "Location": "test",
        "StartTime": "2020-05-04T09:00:00.000Z",
        "EndTime": "2020-05-04T16:00:00.000Z",
        "IsAllDay": false,
        "StartTimezone": null,
        "EndTimezone": null,
        "Description": "test",
        "RecurrenceRule": "FREQ=DAILY;INTERVAL=1;COUNT=5;",
        "Id": 4,
        "CreatedBy": "bob"
    }
],
"client": "Robin",
"hoursWorked": 75,
"kmsTravelled": 880,
"invoiceDate": "2020-04-29T16:37:44.948Z",
"paid": "false",
"subTotal": 3917.2,
"travelexpenses": 167.2,
"tax": 879.7,
"hoursCosts": 3750,
"total": 4796.9,
"createdBy": "bob",
"__v": 0
}

但是在应用程序的使用过程中,某些属性值会发生变化,例如hoursWorkedtotalkmTravelled和。更新的对象被打印到控制台。因此,每当用户打开组件时,我希望它发布整个对象,但如果已经存在具有该客户名称的发票,则仅更新每个发票的这些属性。hourCostsdetailsclient

更新的对象是this.invoice

this.invoice = {
      client: element.Client,
      hourCosts: (element.difference)*this.Client.price,

      hoursWorked: (element.difference),
      kmsTravelled: element.km,


      travelexpenses: this.Client.kmPrice* element.km,


      subTotal: (this.Client.kmPrice* element.km) + ((element.difference)*this.Client.price),
      total: ((this.Client.kmPrice* element.km) + ((element.difference)*this.Client.price)) + ((this.Client.kmPrice* element.km)+((element.difference)*this.Client.price) * this.tax/100),
      createdBy: this.userName,

      details: this.details
     }

那么我该怎么做呢?很抱歉提出一个非常模糊的问题,但我现在坚持了很长时间。如果您需要更多信息,请告诉我

标签: javascriptangularmongodbobjectmongoose

解决方案


您可以通过“id”查询以搜索已更改的特定值,例如:db.getCollection('hourCosts').find({_id:'5ea9ad58f65d8d49841362bd'})

使用 .find() 按 id 在集合中搜索将是有效的。这里有一个非常有用的猫鼬文档页面。

另外,只是澄清一下,如果名称是唯一的,您将发布完整的客户模式,否则通过“客户”更新相关发票,对吗?链接的文档页面应该对大多数查询类型很有用,您可以创建额外的猫鼬模式,以增加您更改内容的粒度。


推荐阅读