如何使用 mongoose 在 MongoDB 中的对象内部进行搜索?

How To Search Inside an Object in MongoDB using mongoose?

这里是'Conversation'集合

的对象结构
{
    "_id" : ObjectId("5536028a33e52be617b8bb2a"),
    "messages" : [
        {
            "from" : ObjectId("5534c58ac2bda5fe18cfcb97"),
            "_id" : ObjectId("5536028a33e52be617b8bb2b"),
            "created" : ISODate("2015-04-21T07:55:54.572Z"),
            "read" : false,
            "message" : "dummy message",
            "participants" : [
                ObjectId("5534c58ac2bda5fe18cfcb97"),
                ObjectId("5530af38576214dd3553331c")
            ]
        }
    ],
    "participants" : [
        ObjectId("5530af38576214dd3553331c")
    ],
    "__v" : 0
}

使用下面的代码我得到了对象

collection.findById(id,function(err,conv){})

现在使用此对象我需要查找参与者数组(在对象内)是否包含对象 ID '5530af38576214dd3553331c'。如何使用猫鼬在对象内部查找?

您可以使用 find() 方法,您的查询对象将具有 idparticipants 字段:

var mongoose = require("mongoose");
var participant_id = mongoose.Types.ObjectId("5530af38576214dd3553331c");
var query = { _id: id, participants: participant_id };

Conversation.find(query)
            .exec(function(err, conv){
               // Handle err
            });

你可以只使用 mongoose find

collection.find({participants: <your participant id here>}).exec(callback)