【问题标题】:How can I copy an entire JavaScript object to update a MongoDB/Mongoose document, that contains nested arrays and subdocuments?如何复制整个 JavaScript 对象以更新包含嵌套数组和子文档的 MongoDB/Mongoose 文档?
【发布时间】:2020-05-07 16:28:53
【问题描述】:

我有一个看起来像这样的架构(最小化/适合问题):

const grandchild = new mongoose.Schema({
    bar: String
}


const child = new mongoose.Schema({
  foo: Number,
  children: [grandchild]
});

const parent = new mongoose.Schema({
  baz: String,
  children: [child]
}

const Parent = mongoose.model("Parent", parent);

并且我需要更新现有的Parent(本质上是替换/复制整个对象)给定来自表达 put 请求正文的 JavaScript 对象,这反映了猫鼬模式确切地说:

{
  baz: "Baz",
  children: [
    {
      foo: 50,
      children: [
        {
           bar: "abc"
        },        
        {
           bar: "xyz"
        }
      ]
    },
    {
       foo: 20
    },
  ]
}

我需要更新一个文档,然后发回更新的版本。

我已经尝试过这样做(假设我知道父文档的 ID):

app.put("/update", (req, res) => {
   const updated = Parent.findOneAndUpdate({_id: id}, req.body, {new: true});

   // (I do convert to something sendable via express, but omitted here as irrelevant 
   res.json(updated)
}

这似乎正确地复制了parentchild 文档,但是子文档数组中的孙对象没有被复制过来,我得到的结果是缺少每个child 子文档的子对象:

{
  baz: "Baz",
  children: [
    {
      foo: 50,
    },
    {
       foo: 20
    },
  ]
}

那么我怎样才能基本上深度复制整个javascript对象来更新猫鼬文档呢?

【问题讨论】:

    标签: javascript node.js mongodb express mongoose


    【解决方案1】:

    原来我在模式模型中有拼写错误,所以它没有正确更新它。

    现在可以了。

    【讨论】:

      猜你喜欢
      • 2021-03-26
      • 2017-04-01
      • 1970-01-01
      • 2016-10-06
      • 2016-11-23
      • 2021-02-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多