【问题标题】:Update Nested Objects with Mongoose使用 Mongoose 更新嵌套对象
【发布时间】:2016-11-02 02:20:57
【问题描述】:

我正在尝试使用 Mongoose 更新嵌套对象。但是当我收到请求时,它看起来像这样:

{
'example[apple]': 'false',
'example[pear]': 'false',
'example[banana]': 'false',
'example[orange]': 'false',
}

我的模型如下所示:

email: {
    type: String,
    index:true,
    unique: true,
},
example: {
  apple: {type:Boolean, default: true},
  banana: {type:Boolean, default: true},
  pear: {type:Boolean, default: true},
  orange: {type:Boolean, default: true}
}

我发送的对象是这样的:

var formData = {
  example: {
    apple: false,
    banana: false,
    pear: false,
    orange: false
  }
}

我做错了什么?

【问题讨论】:

  • 谁在生成和发布请求?是你吗。您的请求的结构与 mongoose 模型彼此不一致。
  • @satishchennupati 我正在生成并发布请求。模型应该如何匹配?

标签: javascript node.js mongodb mongoose mongoose-schema


【解决方案1】:

首先是请求体 { 'example[apple]': 'false', 'example[pear]': 'false', 'example[banana]': 'false', 'example[orange]': 'false', } 是您可以访问的 JSON 对象:example.apple 等。
exampleObject 首先必须是 JSON 对象。 从您的模型看来,示例是模型中的属性,因此要更新您必须选择:
1-是通过不提供文档的ID来更新所有文档:
yourmodel.findAndUpdate({no thing here},exampleObject,callBack)
2-按条件更新;首选: yourmodel.findAndUpdate(condition,exampleObject,callBack)
条件可以是={_id:an id}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-20
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    • 2018-11-10
    相关资源
    最近更新 更多