【问题标题】:Is it possible to query a element in mongoose map by key alone是否可以单独按键查询猫鼬地图中的元素
【发布时间】:2021-12-13 11:34:12
【问题描述】:

如果我有一个带有地图的猫鼬模式。是否可以单独通过键查询地图中的元素

const userSchema = new Schema( {
    
    socialHandles: {
        type: Map,
        of: String
    },
    active: {type:Boolean, default:true}
} );

我可以通过以下语法查询并找到社交句柄具有 instagram 键且 instagram 键具有特定值的用户。

let user = await User.findOne({ 'socialHandles.instagram': 'jondoe' });

如果存在名为 instagram 的键,我正在寻找一种方法来查询和查找用户的 instagram id。下面的形式,即让用户拥有一个社交句柄 instagram(我稍后需要 instagram 的值)。

let user = await User.findOne({ 'socialHandles.instagram': * });  // this is just a wrong syntax to explain what I want to achieve

【问题讨论】:

    标签: javascript node.js mongoose mongoose-schema


    【解决方案1】:

    使用exists

    let user = await User.findOne().exists('socialHandles.instagram')
    

    【讨论】:

      【解决方案2】:

      你可以像这样使用$exists

      User.findOne({
        "socialHandles.instagram": {
          "$exists": true
        }
      })
      

      例如here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-24
        • 2017-03-12
        • 1970-01-01
        • 1970-01-01
        • 2022-12-14
        • 2021-03-04
        • 2019-01-17
        • 2018-02-14
        相关资源
        最近更新 更多