gpt4 book ai didi

node.js - 使用 Mongoose+Node.js 在 MongoDB 中存储非结构化 JavaScript 对象

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

在我的 node.js 应用程序中,我需要在 MongoDB 中存储非结构化 JavaScript 对象。我在 Mongoose 中指定了以下模型:

module.exports = mongoose.model('DBAllocation', {
from: Date,
expires: Date,
userSession: Object,
allocationTimestamp: Date,
allocationPriority: Number,
vmGroupID: String,
allocationRequestContent: Object
});

通过将 userSessionallocationRequestContent 的数据类型指定为 Object 类型,我想将 JavaScript 对象(不指定其结构) 保存到 MongoDB 中并按原样检索它。但是当我将模型保存到数据库中时,出现内部错误。我尝试存储以下项目:

var allocation = new Allocation({
_id: allocationID,
from: Date.now(),
expires: null,
userSession: authorizedRequest.session,
allocationTimestamp: Date.now(),
allocationPriority: <some number>,
vmGroupID: <some number>,
allocationRequestContent: authorizedRequest.requestContent
});

authorizedRequest.sessionauthorizedRequest.requestContent 是两个 JavaScript 对象。但是当我将它们都替换为 {} 时,模型就成功保存了。我听说过 strict 参数,我们可以用它来存储非结构化数据,但我怀疑我是否可以使用它来实现我所需要的。无论如何有办法完成这个吗?任何帮助将非常感激。

更新:

我发现 authorizedRequest.session 是一个 MongoDB 模型,我将其替换为 authorizedRequest.session.toObject() 并将 authorizedRequest.requestContent 替换为一个简单的对象,例如 {'cat': '123', 'dog':'456'} 并成功保存。无法弄清楚发生了什么。

authorizedRequest.requestContent 包含以下对象。

{
"group":[
{
"vm_count":[
"10"
],
"image":[
{
"type":[
"iso"
],
"id":[
"280b40d0-6644-4e47-ac7c-074e2fa40cd4"
]
}
],
"cpu":[
{
"cores":[
"1"
],
"frequency":[
"1"
],
"unit":[
"GHz"
],
"architecture":[
"x86"
]
}
],
"min_memory":[
{
"size":[
"2"
],
"unit":[
"GB"
]
}
],
"min_storage":[
{
"primary":[
"5"
],
"unit":[
"GB"
]
}
],
"network":[
{
"min_bandwidth":[
"8"
],
"unit":[
"mbps"
]
}
],
"priority":[
"3"
],
"allocation_time":[
{
"schedule":[
{
"date":[
{
"$":{
"year":"",
"month":"",
"date":""
}
}
],
"time_from":[
""
],
"time_to":[
""
]
}
]
}
]
}
],
"session_id":[
"3deb1bb861f34b527e6709c655fff139b36c2dc43d8b3e29e3914bf8b23ce069"
]
}

谢谢。

最佳答案

问题可能出在 authorizedRequest.requestContent 对象中的 $ 键,因为 MongoDB 字段名称不能以 $ 开头。

参见the docs可能的解决方法。

关于node.js - 使用 Mongoose+Node.js 在 MongoDB 中存储非结构化 JavaScript 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28317930/

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