How to query collections with mongoose embedded fields?

0

learning mongoose and mongoDB I have an inconvenience that I do not know how to solve, with the following code:

var mongoose = require('mongoose'); 

var mongooseEsquema = new mongoose.Schema({
    nombre: {type: String},
    apellido : {type: String},
    emb_lugares : [{type: new mongoose.Schema({
        localidad: {type: String},
        direccion: {type: String}
    })}]
});
var mongooseModelo = mongoose.model("informacion", mongooseEsquema);

//==================================================================
// docs de prueba almacenados en la coleccion informacion
// [
//     { 
//         nombre: "andres",
//         apellido:"perez",
//         emb_lugares: [
//           {localidad : "Barinas", direccion: "Av colonia # 3"},
//           {localidad : "Mazuela", direccion: "Av libertadoes # 45"},
//         ]
//     },
//     { 
//         nombre: "Sara",
//         apellido:"Gomez",
//         emb_lugares: [
//             {localidad : "Veraguas", direccion: "TR palmas # 85"},
//             {localidad : "Mazuela", direccion: "Av libertadoes # 45"},
//         ]
//     }
// ]

mongooseModelo.find({emb_lugares: {localidad : "Mazuela"}})
.then((dato)=>{
//...Devuelve  dato = null
})
.catch((error)=>{

});

when consulting MongoBD for all the documents whose field location has the value of "Mazuela", it returns null (indicating that it does not find matches), however if I make basic queries about simple fields (such as the name or surname) it works without problems but in fields that contain a {type: new mongoose.Schema ()} I do not know how to build the query

Extending the question a bit more, how can I consult fields (including embedded ones) based on a regular expression?

Thanks for any input.

    
asked by Magner Lesmes 12.06.2018 в 00:28
source

1 answer

0

Access via point notation, as if you accessed directly the nested documents:

mongooseModelo.find({
  'emb_lugares.localidad': {
    $regex: /Ghost/,
    $options: 'i'
  }
})
.then((datos) => {
  // hacer algo
});

Note the key $options ; here you can specify the behavior of the regular expression and pass the flags you want.

    
answered by 12.06.2018 / 00:53
source