猫鼬-如何通过匹配猫鼬对象ID数组中的元素来查找特定文档

时间:2020-09-12 02:03:17

标签: node.js mongodb mongoose

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

<asp:UpdatePanel ID="UpdatePanel" runat="server">
    <ContentTemplate>
        <asp:DropDownList ID="listaClientes" runat="server" ClientMode="Static" OnSelectedIndexChanged="addLabel" AutoPostBack="true"></asp:DropDownList>
    </ContentTemplate>
    <Triggers>
        <asp:AsyncPostBackTrigger ControlID="listaClientes" />
    </Triggers>
</asp:UpdatePanel>

我想找到在投资数组中具有特定var accountSchema = new mongoose.Schema({ accountName: String, accountType: { type: String, default: 'Individual Account' }, accountNumber: { type: String, unique: true }, accountActive: Boolean, investment: [ { type: mongoose.Schema.Types.ObjectId, ref: 'Investment' } ] }) module.exports = mongoose.model('Account', accountSchema); 的{​​{1}}文档。

Account

我尝试了下面的代码,但是我不断得到一个空数组:

object id

我在做什么错?我希望elemMatch可以根据mongoose document运行。在调试时,我看到代码已正确翻译为mongodb。

"investment": [
        {
            "$oid": "5f353184c2daaf0f5c661ea7"
        },
        {
            "$oid": "5f3531acc2daaf0f5c661ea9"
        },
        {
            "$oid": "5f366e873d566938f81b94a8"
        },
]

有人可以在这里帮我吗?

2 个答案:

答案 0 :(得分:0)

find方法可检索整个文档。使用elemMatch作为query operator可以确定从集合中选择了哪个文档。它不会更改子文档数组的内容。

要限制investment数组元素的内容,请将elemMatch用作projection operator

答案 1 :(得分:0)

$elemMatch的文档中,它说:

如果您在$elemMatch表达式中仅指定一个条件,并且未在$not内使用$ne$elemMatch运算符,则$elemMatch可以被忽略。

Query an Array for an Element中:

要查询数组字段是否包含至少一个具有指定值的元素,请使用过滤器{},其中是元素值。

因此,您可以执行以下操作:

Account.find({investment: investment.id}).exec...