本文介绍了如何根据另一个属性选择一个属性-mongodb的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在使用mongoose
.我想根据此处type
上的另一个属性来选择users
属性.
I'm using mongoose
. I want to select users
property depending on another property at this here type
.
例如,当我的type
是private
时,我要选择users
.
for example when my type
is private
I want to select users
.
Conversation.find({
users: {
$elemMatch: {
user: _id
}
}
},{
title: 1,
type: 1,
users:1 // when `type` is `private` I want to this field to be one.
});
我的模式:
const ConversationSchema = new Schema({
type: {type: String, enum: ['private', 'group'], default: 'private'},
creator: {type: Schema.Types.ObjectId, ref: 'User', index: true, required: true}, // creator
// for group,
title: String,
picture: String,
description: String,
users: [
{
user: { type: Schema.Types.ObjectId, index: true, reuqired: true, unique: true },
role: { type: String, enum: ['admin', 'member'], default: 'member' },
mute: { type: Boolean, default: false },
type: {type: String, enum: ['private', 'group'], default: 'private'},
}
],
}, { timestamps: true });
推荐答案
您可以通过使用" rel ="nofollow noreferrer">删除.您的情况应该是:
You can conditionally exclude fields by using REMOVE in aggregation. In your case, it should be:
Conversation.aggregate([
{$match: {"users.user": id}},
{
$project: {
title: 1,
type: 1,
users: {
$cond: {
if: { $eq: [ "$type", "private" ] },
then: "$users",
else: "$$REMOVE"
}
}
}
}
])
旁注:如果在$elemMatch
表达式中仅指定一个条件,则无需使用$elemMatch
.
Side note: If you specify only a single condition in the $elemMatch
expression, you do not need to use $elemMatch
.
这篇关于如何根据另一个属性选择一个属性-mongodb的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!