【问题标题】:MongoDB Mongoose find using MapMongoDB Mongoose 使用 Map 查找
【发布时间】:2020-09-25 07:59:16
【问题描述】:

我有一个像这样的猫鼬模式:

const userSchema = new Schema( {
    email:{ type: String, required: true, unique:true, index:true },
    mobile:{ type: String },
    phone:{ type: String },
    firstname: { type: String },
    lastname: { type: String },
    profile_pic:{type:String},
    socialHandles: {
        type: Map,
        of: String
    },
    active: {type:Boolean, default:true}
}, {
    timestamps: true
} );

我想查询“给我用户 where socialHandles.instagram=jondoe”我该怎么做? 请帮忙

【问题讨论】:

    标签: mongodb mongoose mongodb-query mongoose-schema


    【解决方案1】:

    Mongoose 的地图成为您数据库中的嵌套对象

    { "_id" : ObjectId(""), "socialHandles" : { "instagram": "jondoe" }, ..., "__v" : 0 }
    

    所以你可以使用点符号来查询它:

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

    【讨论】:

    • 谢谢。您将如何在 findone 中将“Instagram”作为 var 提供?
    • 知道了。就像 const findUserBySocialHandle = ( platform, handle ) => User.findOne( { [`socialHandles.${platform}`]:handle});
    • 收到了关于此问题的后续问题。如果 ${platform} 是由两个词组成的呢?
    猜你喜欢
    • 1970-01-01
    • 2013-02-19
    • 2013-02-06
    • 1970-01-01
    • 1970-01-01
    • 2015-12-09
    • 2015-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多