如何使用带有动态键的猫鼬模型模式?

Ahm*_*ndo 4 node.js mongoose-schema

我在 nodejs 中使用猫鼬,我需要创建一个动态模式模型,这是我的代码:

schema.add({key : String});
Run Code Online (Sandbox Code Playgroud)

key = "user_name",但在我的数据库中,我发现模型将其作为键

{ key : "Michele" } and not { user_name: "Michele"}
Run Code Online (Sandbox Code Playgroud)

我能做什么?谢谢你。

Ras*_*ash 9

如果我理解正确,您希望为动态生成add的架构添加一个新列key。例如,可能是每个用户的帖子集合,其中帖子的标题是关键。如果用户创建了一个新帖子,它会被添加到他的收藏中,并将密钥作为其帖子的标题。

当你最初

let schema = new Schema({ id: String, ... , key: String })
Run Code Online (Sandbox Code Playgroud)

猫鼬从key字面上看,就像id从字面上看一样。

不能动态地向模式的根添加键的原因是因为猫鼬不能保证任何结构。strict: false正如其他人所建议的那样,您也可以使整个模式自由形式。

但是,如果您不想使整个架构自由形式,而只是其中的某一部分,您也可以修改架构以使用混合

let schema = new Schema({ id: String, ... , posts: Schema.Types.Mixed })
Run Code Online (Sandbox Code Playgroud)

现在,您可以保存所有动态生成的posts自由格式密钥。

您还可以使用map执行上述操作:

let schema = new Schema({ id: String, ... , posts: {type: Map, of: String} })
Run Code Online (Sandbox Code Playgroud)

这将允许您在posts结构内创建任何键值对。


zan*_*ngw 5

同样的问题schema with variable key在猫鼬中讨论过,

不,目前不可能。最接近的替代方法是使用strict: falsemixed模式类型。

更新

在 Mongoose 5.1.0 之后,我们可以使用术语'map',地图是您使用任意键创建嵌套文档的方式

const userSchema = new Schema({
  // `socialMediaHandles` is a map whose values are strings. A map's
  // keys are always strings. You specify the type of values using `of`.
  socialMediaHandles: {
    type: Map,
    of: String
  }
});

const User = mongoose.model('User', userSchema);
// Map { 'github' => 'vkarpov15', 'twitter' => '@code_barbarian' }
console.log(new User({
  socialMediaHandles: {
    github: 'vkarpov15',
    twitter: '@code_barbarian'
  }
}).socialMediaHandles);

Run Code Online (Sandbox Code Playgroud)