使用猫鼬创建动态模式 [英] Creating dynamic schema using mongoose

查看:83
本文介绍了使用猫鼬创建动态模式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Node js和Mongoose模块非常陌生.我正在尝试创建一个架构,其中有一些必填字段,而其他字段可以是动态的.

I'm very new to Node js and Mongoose module. I'm trying to create a schema, where there are some required fields and some others can be dynamic.

我已经使用strictfalse.我的代码如下:

I have used strict to false. My code looks like this:

var mongoose = require('mongoose')
var db = mongoose.connect('mongodb://localhost/ets',function(err)
{
    if(err) throw err
})

var Schema = mongoose.Schema
var Tasks = new Schema({vmProfile:String}, { strict: false });
mongoose.model('Task',Tasks)

var Task = mongoose.model('Task')
var task = new Task()
task.vmProfile = "required value"
task.otherKey = "something"
task.save(function(err)
{
    if(err) throw err;
})

运行此命令时,只保存了vmProfile而不是otherKey,数据库看起来像这样:

when I run this , I get only the vmProfile saved, not otherKey, the DB looks like this:

{ "vmProfile" : "required value", "_id" : ObjectId("53364a5a5cd71a76122f0a8a"), "__v" : 0 }

我在哪里弄错了.

推荐答案

来自猫鼬文档:

注意:您的实例上不存在的实例上设置的任何键/值 无论选择哪种模式,总是会忽略模式.

NOTE: Any key/val set on the instance that does not exist in your schema is always ignored, regardless of schema option.

您可以在创建模型实例时设置值:

You can set the value when the model instance is created:

var task = new Task({'otherKey', 'some value'});

您还可以将临时值放在混合下子文档类型.

You could also put the ad-hoc values under a mixed subdocument type as well.

这篇关于使用猫鼬创建动态模式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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