如何在猫鼬中查找和更新数组中的元素?

How to find and update an element in an array in mongoose?

我有以下架构。每个商店都有一个 ID 和一个存储桶列表。

const storeSchema = new mongoose.Schema({
    _id: String
    bucket: [
        {
            sold: Boolean,
            location: {
                state: String,  
                location: String,
                description: String,
            },
            fruits: [          
                {
                    item: String,      // apple, pear, orange
                    status: String,  // fresh, ripe, rotten
                    completed: Date
                }
            ]
        }
    ]
}, {collection: 'store'});

现在我有一个有两个桶的商店,如下所示。我想编辑第一个桶(在 MongoDB 中的索引位置为 0)。我怎样才能做到这一点?另外,如何在不对同一桶中的其他水果或其他桶中的任何水果进行任何更改的情况下,将第一个桶苹果的状态从“新鲜”更改为“成熟”?

{
    _id: "1"
    bucket: [
        {
            sold: false,
            location: {
                state: "CA",  
                location: "LA",
                description: "something",
            },
            fruits: [          
                {
                    item: "apple",      // apple, pear, orange
                    status: "fresh",  // fresh, ripe, rotten
                    completed: null
                },
                {
                    item: "pear",      // apple, pear, orange
                    status: "fresh",  // fresh, ripe, rotten
                    completed: null
                },
            ]
        },
        {
            sold: false,
            location: {
                state: "CA",  
                location: "LA",
                description: "something",
            },
            fruits: [          
                {
                    item: "apple",      // apple, pear, orange
                    status: "fresh",  // fresh, ripe, rotten
                    completed: null
                },
                {
                    item: "orange",      // apple, pear, orange
                    status: "fresh",  // fresh, ripe, rotten
                    completed: null
                },
            ]
        },
    ]
}

简而言之: 如何将此商店中的第一个存储桶(索引 0)从 sold: false 更改为 sold: true 及其 fruits item: 'apple'status'fresh''ripe' 使用猫鼬。

对 Store 模型执行 findOne 查询并手动更新索引 0 处的商店。

然后调用store.save()方法

Store.findOne({ _id: 1 }).then(store => {

  if (!store) {
    return 'Store not found';
  }

  store.bucket[0].solid  = true;
  store.bucket[0].fruit  = store.bucket[0].fruit.map(x => {
    if (x.item === 'apple') {
      x.status = 'ripe';
    }
    return x
  });

  store.save();
});

如果水果不存在,则将橙色项目添加到水果中

const orange = store.bucket[0].fruit.find(x => x.item === 'orange');

if (!orange) {
  store.bucket[0].fruit.push({
    item: 'orange',
    status: 'fresh',
    completed: null
  })
}