admin管理员组文章数量:1429449
If I have a mongoose schema with a map. Is it possible to query a element in the map by key alone
const userSchema = new Schema( {
socialHandles: {
type: Map,
of: String
},
active: {type:Boolean, default:true}
} );
I am able to query and find a user whose social handles has instagram key and instagram key holds a particular value with the below syntax.
let user = await User.findOne({ 'socialHandles.instagram': 'jondoe' });
I am looking for a way to query and find the instagram ids of user if a key called instagram exists. Something of the below form ie get a user with a social handle instagram ( I would need the value of instagram later on).
let user = await User.findOne({ 'socialHandles.instagram': * }); // this is just a wrong syntax to explain what I want to achieve
If I have a mongoose schema with a map. Is it possible to query a element in the map by key alone
const userSchema = new Schema( {
socialHandles: {
type: Map,
of: String
},
active: {type:Boolean, default:true}
} );
I am able to query and find a user whose social handles has instagram key and instagram key holds a particular value with the below syntax.
let user = await User.findOne({ 'socialHandles.instagram': 'jondoe' });
I am looking for a way to query and find the instagram ids of user if a key called instagram exists. Something of the below form ie get a user with a social handle instagram ( I would need the value of instagram later on).
let user = await User.findOne({ 'socialHandles.instagram': * }); // this is just a wrong syntax to explain what I want to achieve
Share
Improve this question
asked Oct 28, 2021 at 9:01
ArunJoseArunJose
2,1742 gold badges13 silver badges34 bronze badges
3 Answers
Reset to default 5You can use $exists
like this:
User.findOne({
"socialHandles.instagram": {
"$exists": true
}
})
Example here
Use exists
let user = await User.findOne().exists('socialHandles.instagram')
When I do this
await User.findOne().exists('socialHandles.instagram');
it returns the entire Map. If someone wants to get the individual item (how I got here) we can do this:
const map = await User.findOne();
const user = user.get('socialHandles.instagram');
Also using this method we can get the entire Map by omitting .instagram:
const user = user.get('socialHandles');
本文标签: javascriptIs it possible to query a element in mongoose map by key aloneStack Overflow
版权声明:本文标题:javascript - Is it possible to query a element in mongoose map by key alone - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745491148a2660609.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论