简体   繁体   English

使用 Mongoose 从对象数组中获取和操作键的值

[英]Getting and manipulating a value of a key from an array of objects using Mongoose

This is a document from my profiles collection:这是我的个人资料集合中的一个文档:

{
    _id: ObjectId("5f2ba3a43feccd0004b8698c")
    userID: "238906554584137728",
    serverID: "533691583845892100",
    username: "W.M.K",
    money: 15775,
    __v: 4,
    items: [...],
    serverName: "W-15i: Overworld",
    gladium: 7959.33,
    stocks: [{
        _id: {...},
        stockID: "605b26d309a48348e05d88c9",
        name: "GOOGL",
        amount: 1,
        desc: "Alphabet Inc's (Google) Stock."
    }]
}

I'm using const profile = await Profile.findOne({userID: userID, 'stocks.stockName': stock.name})我正在使用const profile = await Profile.findOne({userID: userID, 'stocks.stockName': stock.name})

EDIT: For one stock, it's as easy as profile.stocks[0].amount -=1 .编辑:对于一只股票,它就像profile.stocks[0].amount -=1一样简单。 But when I have multiple stocks, how do I get the amount and manipulate it like amount -= 1 ?但是当我有多个股票时,我如何获得amount并像amount -= 1一样操纵它?

there are few ways you can go through an array of objects in mongoose... you can map through the array, you can also use dot notation in an update.有几种方法可以通过 mongoose 中的对象数组 go ... 您可以通过数组 map,也可以在更新中使用点表示法。 Either way one thing you'll need to do is mark the document modified because mongo doesn't detect changes in arrays of objects.无论哪种方式,您需要做的一件事是将文档标记为已修改,因为 mongo 没有检测到对象 arrays 的更改。 To do this, make the changes and then use the markModified() function on the document.为此,请进行更改,然后在文档上使用 markModified() function。 It takes a parameter of the array field name that was modified.它采用已修改的数组字段名称的参数。 in this case.... profile.markModified('stocks')在这种情况下.... profile.markModified('stocks')

This is done after changes and before the save.这是在更改之后和保存之前完成的。

You can use dot notation with mongoose and you can also iterate through the array via map or forEach您可以将点表示法与 mongoose 一起使用,也可以通过 map 或 forEach 遍历数组

The benefit of using map is that you can double it up with.filter() to filter the array for certain stocks使用 map 的好处是您可以将其加倍使用 .filter() 来过滤特定股票的数组

As already stated by Jeremy, it is basically a matter of array manipulations.正如 Jeremy 已经说过的,这基本上是数组操作的问题。 Here is one example:这是一个例子:

for(let i = 0; i < profile.stocks.length; i++) { 
 profile.stocks[i].amount -= 1;
}

If you just want to update the profile on your database, you could also look into some very advanced mongodb querys (I think it's called "aggregation"), but that is probably overkill.如果您只想更新数据库上的配置文件,您还可以查看一些非常高级的 mongodb 查询(我认为它称为“聚合”),但这可能是矫枉过正。

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

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