在MongoDB中使用Mongoose + Node.js存储非结构化的JavaScript对象
在我的node.js应用程序中,我需要在MongoDB中存储非结构化的JavaScript对象。 我在Mongoose中指定了以下模型:
module.exports = mongoose.model('DBAllocation', { from: Date, expires: Date, userSession: Object, allocationTimestamp: Date, allocationPriority: Number, vmGroupID: String, allocationRequestContent: Object });
通过指定userSession
和allocationRequestContent
的数据types为Object
types,我想将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.session
和authorizedRequest.requestContent
是两个JavaScript对象。 但是当我用{}
replace它们时,模型会成功保存。 我听说过我们可以用来存储非结构化数据的strict
参数,但是我怀疑是否可以用它来实现我所需要的。 有没有办法来实现这个呢? 任何帮助将非常感激。
更新:
我发现authorizedRequest.session
是一个MongoDB模型,我用authorizedRequest.session.toObject()
replace了它,并用一个简单的对象{'cat':'123','dog':'456'replaceauthorizedRequest.requestContent
, }并保存成功。 无法弄清楚发生了什么事。
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
对象中的$
key作为MongoDB字段名称不能以$
开头。
请参阅文档以了解可能的解决方法。