gpt4 book ai didi

javascript - Mongoose 保存数组的数组而不是单个数组

转载 作者:太空宇宙 更新时间:2023-11-04 03:23:32 25 4
gpt4 key购买 nike

我正在尝试使用 mongoose 在 MongoDB 上保存数组。这是我的模型:

let itemFields = { "name": { "type": "String", "required": true, "unique": true } };

let modelFields = {
"name": { "type": "String", "required": true, "unique": true },
"description": { "type": "String" },
"options": { "type": "Array", "ref": "SelectOptionItem" },
"company_id": { "type": "ObjectId", "ref": "Company", "required": true },
"deleted": { "type": "Boolean", "required": true },
"createdAt": { "type": "Number" },
"updatedAt": { "type": "Number" }
};

const SelectOptionItem = new mongoose.Schema(itemFields);
const schema = new mongoose.Schema(modelFields);

后来我有以下代码来保存数据:

schema.statics.create = async function(context, data) {
console.log("Saved data:");
console.log(data);
let so = new this(data);
so.save();
}

我在哪里得到以下日志:

 Saved data:
{ name: 'aa',
description: 'aa',
options: [ { name: '1' }, { name: '2' } ],
company_id: '59b2cd9a072e4f28b839aaa0',
deleted: false,
createdAt: 1511569192524 }

最后,这就是我在 mongo 控制台中得到的内容:

> db.selectoptions.find({});
{ "_id" : ObjectId("5a18b7288c688033a4adcb0c"), "name" : "aa", "description" : "aa", "company_id" : ObjectId("59b2cd9a072e4f28b839aaa0"), "deleted" : false, "createdAt" : 1511569192524, "options" : [ [ { "name" : "1" } ], [ { "name" : "2" } ] ], "__v" : 0 }

修复选项是一个数组的数组([[]])。稍后,当检索该数据时,我遇到了问题,因为我期待单个数组。

我需要理解为什么 mongoose 在 options 字段中保存数组的数组以及如何解决这个问题。

最佳答案

更改此行:

"options": { "type": "Array", "ref": "SelectOptionItem" },

这样:

"options": { "type": "Mixed", "ref": "SelectOptionItem" },

或者这样:

"options": [SelectOptionItemSchema],

第二个生成项目的_id

关于javascript - Mongoose 保存数组的数组而不是单个数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47481539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com