我在 nodejs 中使用猫鼬,我需要创建一个动态模式模型,这是我的代码:
schema.add({key : String});
key = "user_name",但在我的数据库中我发现模型将其作为键
{ key : "Michele" } and not { user_name: "Michele"}
我能做些什么?谢谢你。
我在 nodejs 中使用猫鼬,我需要创建一个动态模式模型,这是我的代码:
schema.add({key : String});
key = "user_name",但在我的数据库中我发现模型将其作为键
{ key : "Michele" } and not { user_name: "Michele"}
我能做些什么?谢谢你。
如果我理解正确,您希望为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
。
同样的问题schema with variable key
在猫鼬中被谈论,
不,目前不可能。最接近的替代方法是使用
strict: false
或mixed
模式类型。
更新
在 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);
const options = {};
options[key] = String;
schema.add(options);
你可以这样做:
posts: { type: Object }
在 posts 键中,您可以实现任何您想要的键值对