如何在数组中查找作为Schema中的子元素的元素


likes: {
count:{type: Number, default: 0},
authors:{type: [String], default: []}
}

这是点赞部分的模式。我想看看给定的用户名是否在authors数组中?如何为这种情况创建查询?

await Entry.findOne({ 'likes.authors': { $in: user.username },_id: entryId } )

我创建了一个这样的查询,但我无法获取数据,因为我有一个包含entryId'likes.authors'中包含user.username的数据。

试试这个:

Entry.findOne({'likes.authors': {$elemMatch: {type: user.username}},_id:entryId});

最新更新