mongoose嵌套数组模式

时间:2017-11-15 15:39:35

标签: node.js mongodb

我正在尝试为以下数组创建架构:

const data = [ [ { name: 'AKA_A2',
      path: '/',
      expires: 1510762544.752427,
      size: 7 },
    { name: 'userInfo',
      path: '/',
      expires: 0,
      size: 82 },
    { name: 'userInfo',
      path: '/',
      expires: 0,
      size: 82 } ] ]

这是我创建的Schema

import mongoose from 'mongoose';

const CookieSchema = mongoose.Schema(
  {
    name: String,
    path: String,
    expires: String,
    size: String
  }
)

const RunSchema = mongoose.Schema(
  {
    reports: {
      cookieSummary: [CookieSchema]
    }
  }
)

export default mongoose.model('Run', RunSchema);

然后,当我尝试从此架构更新文档时,我收到null响应,文档未更新。

这是我的代码:

Run.findOneAndUpdate({_id: runId}, {$set: {'reports.cookieSummary': data}}, (err, doc) => {
  console.log(doc);
});

我的文档如下:

{
    "_id": {
        "$oid": "5a0c5e86d4b737549e88d8cf"
    },
    "reports": {},
    "__v": 0
}

2 个答案:

答案 0 :(得分:0)

尝试将架构更改为

const RunSchema = mongoose.Schema(
  {
     reports: {
        cookieSummary: [[CookieSchema]]
     }
  }
)

答案 1 :(得分:0)

//在上一个答案中没有为您的答案清除。您不需要创建两个架构

import mongoose from 'mongoose';
const RunSchema = mongoose.Schema({
    reports: {
            cookieSummary: {
                  name: String,
                  path: String,
                  expires: String,
                  size: String
             }
        }
})

export default mongoose.model('Run', RunSchema);