如何在 Mongoose 文档中允许自由格式的 JSON 数据? [英] How to allow free-form JSON data within Mongoose documents?

查看:15
本文介绍了如何在 Mongoose 文档中允许自由格式的 JSON 数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 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.

如何禁用 mongoose 对该字段的验证?

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) 上调用 markModified(path) 来通知 Mongoose 您已更改其值code>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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆