Wednesday, 10 May 2017

MongoDB/Mongoose query. Check if array contains two ObjectId

I'm trying to figure out how to make a query in MongoDB and Mongoose. I have a collection named "Conversacion" which have an array of participants and an array of Mensajes..

My Schema in Mongoose

const Schema = mongoose.Schema;

const ConversacionSchema = new Schema({

        participantes: [
            {
                type: Schema.Types.ObjectId,
                ref: 'Usuario'
            }
        ]

        ,
        mensajes: [
            {
                type: String,
                ref: 'Mensaje'
            }
        ]
    }
    )
;

module.exports = mongoose.model('Conversacion', ConversacionSchema);

db.conversacions.findOne( { } ) returns this:

{
        "_id" : ObjectId("59131d049806b307d04bc53e"),
        "updatedAt" : ISODate("2017-05-10T14:00:36.349Z"),
        "createdAt" : ISODate("2017-05-10T14:00:36.349Z"),
        "mensajes" : [ ],
        "participantes" : [
                ObjectId("591300d1f8f75b127c626481"),
                ObjectId("5913198eeefdb71e9caa0672")
        ],
        "__v" : 0
}

but now I want a query that returns the conversation only if the array "participantes" (participants in english) contains these two ObjectsID, no matter the position (conversations can be created in both ways). Hope I'm explaining well. Thanks.



via Pablo Mora

No comments:

Post a Comment