无法在猫鼬中保存地图



我无法在猫鼬中保存地图

这是我的模式

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,
},
});

有什么帮助吗?

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

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

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

最新更新