4

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

schema.add({key : String});

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

{ key : "Michele" } and not { user_name: "Michele"}

我能做些什么?谢谢你。

4

4 回答 4

9

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

当你最初做

let schema = new Schema({ id: String, ... , key: String })

猫鼬从key字面上理解,就像它从id字面上理解一样。

您不能动态地将键添加到模式的根目录的原因是因为 mongoose 不能保证任何结构。正如其他人所建议的那样,您最好strict: false使整个模式自由形式。

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

let schema = new Schema({ id: String, ... , posts: Schema.Types.Mixed })

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

您也可以使用map进行上述操作:

let schema = new Schema({ id: String, ... , posts: {type: Map, of: String} })

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

于 2019-03-26T03:24:30.623 回答
6

同样的问题schema with variable key在猫鼬中被谈论,

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

更新

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

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);

于 2016-03-26T00:25:14.173 回答
1
const options = {};
options[key] = String;

schema.add(options);
于 2020-06-02T12:21:21.810 回答
0

你可以这样做:

posts: { type: Object }

在 posts 键中,您可以实现任何您想要的键值对

于 2019-08-13T16:13:19.413 回答