Mongoose 变量键名 [英] Mongoose variable key name

查看:21
本文介绍了Mongoose 变量键名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 mongo 对象,并希望通过 mongoose 为我的网络应用程序访问它.我定义的架构有一个 Object 存储用户 ID 和一个 3 级值(是的,可能或否).

I have a mongo object and wish to access it via mongoose for my web app. The schema I've defined has an Object storing user ids and a 3-level value (yes, maybe or no).

例如

"user_info": {
    "<id_value_1>": "y",
    "<id_value_2>": "n"
}

上面的 id_value_* 是用户会话 ID,因此是一长串随机字符.如何为此创建 mongoose Schema ?

The id_value_*s above are the users session ids so a long string of random characters. How can I create a mongoose Schema for this?

  1. user_info: {String, String} 会起作用吗?

我可以重构它,以便 user_info 是一个对象数组 { "sessionid": "<value>", "value: "y"},这没问题,这是最好的选择吗?

I could restructure it so that the user_info is an array of objects { "sessionid": "<value>", "value: "y"}, which would be ok, is this the best option?

推荐答案

如果您在架构中避免使用动态键并采用您的第二个想法:

You'll be better off if you avoid dynamic keys in your schema and go with your second idea of:

user_info: [{sessionid: String, value: String}]

您可以使用 $ 位置运算符来更新单个 user_info 数组元素按 sessionid.

You can use the $ positional operator to update individual user_info array elements by sessionid.

这篇关于Mongoose 变量键名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆