node.js - 使用 Mongoose 创建动态模式

标签 node.js mongodb mongoose

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

我用strictfalse。我的代码如下所示:

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,数据库看起来像这样:

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

我在哪里犯了错误。

最佳答案

来自 Mongoose docs :

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

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

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

您也可以将临时值放在 mixed 下子文档类型也是如此。

关于node.js - 使用 Mongoose 创建动态模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22726972/

相关文章:

javascript - 在哪里存储 JWT Client Credentials Grant

javascript - 在 Node JS 中更改函数的上下文

javascript - 通过属性获取MongoDB中存储的数组

node.js - 如何使用 .d.ts 文件

node.js - 使用带有条件的 mongoose 进行 mongodb 查询哪个更快?

javascript - 日志未使用 JWT 记录在 NodeJS 中

javascript - 为什么在一种情况下我在 ExpressJS 中遇到 cors 错误,而在另一种情况下却没有?

node.js - 如何在 Node mongodb游标上批量处理文档而不超时

Node.js mongoose 更新文档

javascript - 如何有条件地使用开发或生产环境变量