node.js - 在 Mongoose 中如何声明动态 Schema

标签 node.js schema mongoose

我是 Mongoose 的新手,在官方文档中我没有找到任何与我需要的内容相关的内容。

如何声明动态的子架构?

例如:

var A = new Schema({
    name        : String,
    subtype     : String,
    description : String
});

var B = new Schema({
    name        : String,
    description : String
});

var C = new Schema({
    name        : String,
    type        : [if(type.value == 'A') then uses Schema-A;
                   if(type.value == 'B') then uses Schema-B;
                  ]
});

希望这是有道理的。

提前致谢。

最佳答案

您可以将架构的自定义部分的类型设置为 {},然后验证流入的不同结构。请参阅 this gist 。它不如为不同的情况设置不同的模式那么好,但它应该能达到目的。本质上,通过这种方式设置,您实际上是在说文档的该部分没有架构。将架构视为文档的确定部分,这里唯一的确定部分是动态部分的占位符。

我认为,您还可以将每个不同的结构创建为不同的架构,但存储在同一集合中,预先选择适当的架构。我从未尝试过这样做,但由于底层 MongoDB 的无模式性质,应该允许这样做。

关于node.js - 在 Mongoose 中如何声明动态 Schema,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11488256/

相关文章:

node.js - 如何使用 mongoose 在 updateOne 中使用 $cond?

JavaScript/Node.JS - 使用 OR 运算符的紧凑方式?

mysql - 将 mySQL Express Node 转为 Json

database-design - 数据库本地化

javascript - 有没有办法摆脱[对象: null prototype] in GraphQL

json - Mongoose查询结果是只读的吗?

javascript - 无法在类中使用 this 调用函数

javascript - Node.js 全局要求

database - Postgres-Golang-模式与数据库?

node.js - 在 Mongoose 中填写所有必填字段