如何在Mongoose文档中允许自由格式的JSON数据? [英] How to allow free-form JSON data within Mongoose documents?
问题描述
我正在使用 Mongoose ODM 对模型进行部分验证,然后再将模型存储到MongoDB中
I'm using Mongoose ODM to partially validate models before they are stored to MongoDB.
是否可以放松Mongoose模式,以便不验证文档的给定部分?我尝试了以下操作:
Is it possible to relax Mongoose schemata so that a given part of the document is not validated? I have tried to the following:
var MySchema = new Schema({
user_id: { type: Schema.ObjectId, ref: 'User' },
freeform_data: {},
});
例如,如果我将内容设置为:
For instance if I set the contents to:
{
user_id: '123456',
freeform_data: {
dataitem1: 'a',
dataitem2: 'b',
items: [ 1, 2, 3, 4 ]
}
}
然后仅存储user_id
,这在安全性方面完全有意义.
Then only user_id
is stored, which makes perfectly sense security-wise.
如何禁用此字段的猫鼬验证?
How can I disable mongoose's validation for this field?
我仅将此应用程序用于原型设计,所以我现在不关心安全性(我只是想制作原型).
I am using this application only for prototyping purposes so I don't care about security right now (I just want to prototype).
推荐答案
修改 Mixed
字段(如freeform_data),您需要通过在修改后的文档上调用markModified(path)
来通知Mongoose您已更改其值,否则后续的save()
调用将无法保存它.
When you modify the contents of a Mixed
field like freeform_data, you need to notify Mongoose that you've changed its value by calling markModified(path)
on the modified document or a subsequent save()
call won't save it.
例如:
user.freeform_data = { foo: 'bar' };
user.markModified('freeform_data');
user.save();
这篇关于如何在Mongoose文档中允许自由格式的JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!