【问题标题】:How to update a single field in a Contentful entry?如何更新内容条目中的单个字段?
【发布时间】:2022-01-28 22:27:52
【问题描述】:

需要帮助更新 CF 条目中的字段。它是一个没有默认值的下拉字段。

我试图通过从 CF 环境中获取条目、设置相应的字段并像这样更新它来做到这一点:

        client.getSpace(spaceId)
        .then((space) => {space.getEnvironment(environment)
            .then((environment) => {environment.getEntry('1234567890')
                .then((entry) => {
                    entry.fields = {
                        state: {
                            'en-US': 'Arizona'
                        }
                    }
                    return entry.update()
                })
            })
        })

通过这样做,state 值得到更新,但其他现有字段值被删除。

内容更新的内容文档在此处声明相同:https://www.contentful.com/developers/docs/references/content-management-api/#/introduction/updating-content,但我找不到实施他们建议的方法。

如何在不丢失所有其他字段的情况下更新 state 值?

【问题讨论】:

    标签: javascript contentful contentful-management


    【解决方案1】:

    当你这样做时

    entry.fields = {
      state: {
        'en-US': 'Arizona'
      }
    }
    

    您将整个 fields 对象替换为仅包含一个键的新对象:state
    而不是设置entry.fields,你应该设置entry.fields.state

    例子:

    client.getSpace(spaceId)
        .then(space => space.getEnvironment(environment))
        .then(environment => environment.getEntry('1234567890'))
        .then(entry => {
            entry.fields.state = {
                'en-US': 'Arizona'
            }
            return entry.update()
        });
    

    另外:我改变了你使用.then()的方式。 Promises 的好处之一是您不必嵌套回调。在这里,您正在嵌套回调。您可以链接.then() 调用以使您的代码更具可读性,就像我在上面的示例中所做的那样。见:Aren't promises just callbacks?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-11-07
      • 2018-02-01
      • 2017-07-14
      • 1970-01-01
      • 2020-01-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多