【问题标题】:Cannot save map in mongoose无法在猫鼬中保存地图
【发布时间】:2021-09-25 06:13:15
【问题描述】:

我无法在猫鼬中保存地图

这是我的架构

const tempSchema = new mongoose.Schema({
      month: {
        type: Map,
        of: new mongoose.Schema({
          date: {
            type: Map,
            of: Number,
          },
          countries: {
            type: Map,
            of: Number,
          },
        }),
      },
    });

const yearsSchema = new mongoose.Schema({
    years : [ tempSchema ]
  })

我插入数据如下

 const date = new Map();
        date.set("1", 90);
        date.set("2", 23);
        date.set("5", 28);
        date.set("19", 282);
        date.set("23", 18);
        const countries = new Map();
        countries.set("AFGHANISTAN", 90);
        countries.set("TIRANA", 23);
        countries.set("ALGIERS", 28);
        countries.set("LUANDA", 282);
        countries.set("YEREVAN", 18);
        const month = new Map();

        month.set("JANUARY", { date: date, countries: countries })
        const newYear = new Years()
        newYear.years.push(month)
        newYear.save()
     

当它成功保存时,我查看了我的 mongoDB 数据库,我只看到了一个 _id 的文档,没有别的,首先我教它是因为嵌套,我尝试不嵌套, 结果还是一样,只是一个 _id

const tempSchema= new mongoose.Schema({
  month: {
    type: Map,
    of: Number,
  },
});

有什么帮助吗?

【问题讨论】:

  • 我试了你的例子,按预期保存了,是不是newTemp.save()前面少了await的问题?
  • 您可以尝试将它嵌入到一个数组中,例如,将它嵌入到另一个新架构中,例如 new Schema( { years: [ tempSchema ] }

标签: javascript node.js mongodb mongoose


【解决方案1】:

当你推送到一个数组时,你需要传递一个代表tempSchema的对象,所以你的代码应该如下所示:

const newYear = new Years()
newYear.years.push({month});

await newYear.save();

在您的情况下,您直接推送 JavaScript Map,这与 yearsSchema 预期的不同。

【讨论】:

    猜你喜欢
    • 2016-02-09
    • 2016-06-29
    • 2015-02-05
    • 2015-03-27
    • 2018-06-24
    • 1970-01-01
    • 2014-11-07
    • 1970-01-01
    • 2018-04-10
    相关资源
    最近更新 更多