【问题标题】:Updating a schema within a schema Mongoose在模式 Mongoose 中更新模式
【发布时间】:2021-10-07 14:21:06
【问题描述】:

一直在尝试更新我文档中嵌套数组中的字段。

例如这里的示例架构..

childSchema = new Schema ( {
foo2 : String,
bar2 : String,
foobar : String
) };

在此架构内

parentSchema = new Schema ( {
foo1 : String,
bar1 : String,
nested : [childSchema]
)};

如果我想根据 foo2 匹配的字符串更新 bar2 (childSchema),我该怎么做?

我已经尝试了以下,

parentSchema.childSchema.updateOne( { 'nested.foo2' : 'string-that-matches' }, { $set: { 'nested.$.bar2' : 'new-string-for-bar2' } } )

我通常会得到错误

TypeError: Cannot read property 'updateOne' of undefined

我以前没有这样的 childSchema,它只是在 parentSchema 中创建的。更多的是用于测试将它们分离出来。

如果我把这个问题的格式设置错了,我很抱歉,显然我试图从我的真实事物中做一个模拟模式集。我认为我的查询比设置更重要。

谢谢!

【问题讨论】:

    标签: javascript mongodb mongoose mongoose-schema nested-documents


    【解决方案1】:

    parentSchema 这个更新就够了

    parentSchema.updateOne( { 'nested.foo2' : 'string-that-matches' }, { $set: { 'nested.$.bar2' : 'new-string-for-bar2' } } )
    

    【讨论】:

    • 这是正确的。我遇到了一些其他数据问题,这些问题不允许我更新。感谢您的回复!
    猜你喜欢
    • 1970-01-01
    • 2017-10-22
    • 2017-10-06
    • 2011-11-25
    • 1970-01-01
    • 2022-01-15
    • 2021-03-06
    • 2011-11-28
    • 2018-09-26
    相关资源
    最近更新 更多