MongoDB Mongoose使用Map进行数据查找

3

我有一个像这样的mongoose模式:

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

我想查询“给我socialHandles.instagram=jondoe的用户”,该如何操作?请帮忙。

1个回答

6

Mongoose 的 map 在数据库中变成了嵌套对象

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

因此,您可以使用点表示法进行查询:
let user = await User.findOne({ 'socialHandles.instagram': 'jondoe' });

谢谢。您如何将“Instagram”作为变量提供给findone函数? - Ali Nahid
明白了。这段代码类似于 const findUserBySocialHandle = ( platform, handle ) => User.findOne( { [socialHandles.${platform}]:handle}); - Ali Nahid
这个问题有一个后续问题。如果 ${platform} 由两个单词组成怎么办? - barudo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接