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

时间:2021-02-22 20:17:57

标签: javascript mongodb mongoose mongoose-schema

我有以下架构。每个商店都有一个 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 从 {{1} } 到 'fresh' 使用猫鼬。

1 个答案:

答案 0 :(得分:0)

对 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
  })
}