gpt4 book ai didi

arrays - 无法使用 Mongoose 将嵌套 JSON 数组存储到 MongoDB

转载 作者:太空宇宙 更新时间:2023-11-04 01:46:16 26 4
gpt4 key购买 nike

我在 Postman 上有这样的 JSON:

{
"hostname": [
{
"item": [
{
"system": "10l313",
"severity": "2"
},
{
"system": "2131414",
"severity": "3"
}
]
},
{
"item": [
{
"system": "4234235",
"severity": "4"
}
]
}
]
}

我想从上面的 json 在 mongodb 中创建新的集合。这只是实际 json 数组的一小部分图片,上面的 json 数组可以包含一个巨大的数组。我很困惑如何使用 mongoose 保存尽可能多的 json 数组,我是否必须循环数组长度,或者还有其他更简单的方法吗?

Mongoose 架构:

var ItemSchema =  new Schema({
_id: mongoose.Schema.Types.ObjectId,

system: {
type: String
},

severity: {
type: Number
}
})

var VulnSchema = new Schema({

hostname: [{
item: [{ItemSchema}]
}]

});

Controller :

exports.create_vulnerabilities = function (req, res) {
var vuln = new Vuln ({
_idFIle: mongoose.Types.ObjectId(),
hostname: req.body.hostname
});
vuln.save()
.then(result => {
res.status(201).json({
result
});
})
.catch(err => {
console.log(err);
res.status(500).json({
error: err
});
});

};

我尝试运行我的代码,但结果是这样的。问题是系统和严重性属性未存储在 mongodb 中。

{
"_id" : ObjectId("5b4c39a301651a0fc047bec7"),
"hostname" : [
{
"_id" : ObjectId("5b4c39a301651a0fc047beca"),
"item" : [
{
"_id" : ObjectId("5b4c39a301651a0fc047becc")
},
{
"_id" : ObjectId("5b4c39a301651a0fc047becb")
}
]
},
{
"_id" : ObjectId("5b4c39a301651a0fc047bec8"),
"item" : [
{
"_id" : ObjectId("5b4c39a301651a0fc047bec9")
}
]
}
],
"__v" : 0
}

请帮助我。谢谢

最佳答案

改变

var VulnSchema = new Schema({
hostname: [{
item: [{ItemSchema}]
}]
});

var VulnSchema = new Schema({
hostname: [{
item: [ItemSchema]
}]
});

尝试运行示例:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/test');

const Schema = mongoose.Schema,ObjectId = Schema.ObjectId;

var ItemSchema = new Schema({
_id: mongoose.Schema.Types.ObjectId,

system: {
type: String
},

severity: {
type: Number
}
})

var VulnSchema = new Schema({
hostname: [{
item: [ItemSchema]
}]
});

const Vuln = mongoose.model('Vuln', VulnSchema);

var hostname = [
{
"item": [
{
"system": "10l313",
"severity": "2"
},
{
"system": "2131414",
"severity": "3"
}
]
},
{
"item": [
{
"system": "4234235",
"severity": "4"
}
]
}
]

var vuln = new Vuln ({
_idFIle: mongoose.Types.ObjectId(),
hostname: hostname
});

vuln.save()
.then(result => {
console.log(JSON.stringify(result))
})
.catch(err => {
console.log(err);}
);

关于arrays - 无法使用 Mongoose 将嵌套 JSON 数组存储到 MongoDB,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51355792/

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