Filtering json data with schema attribute

1

I have JSON in this format:

{
 "1": {
   "cidade":"cidade1",
   "name":"nome1"
 },
 "2": {
   "cidade":"cidade2",
   "name":"nome2"
 }
}

I need to filter the data from this json. For this I made a model.js

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var MySchema = new Schema({cod: Number, cidade: String, nome: String});

module.exports = mongoose.model('My', MySchema);

and a routes.js

module.exports = function(router, My) {

    router.route('/my')
        .get(function(req, res) {
            My.find(function(err, my) {
                if (err)
                    res.send(err);

                res.json(my);
            });
        });

    router.route('/my/:my_id')
        .get(function(req, res) {
            My.findById(req.params.my_id, function(err, my) {
                if (err)
                    res.send(err);

                res.json(my);
            });
        })
}

My problem is this: I want to filter by my cod attribute and not by the generated mongoose id in a way where I type /my/1 and it returns me

{
 "1": {
   "cidade":"cidade1",
   "name":"nome1"
 }
}

I have tried in many ways but I could not. I tried via query:

router.route('/my/:cod')
        .get(function(req, res) {
            My.find(function(err, my) {
                if (err)
                    res.send(err);

                res.json(my);
            }).where('my.cod').equals(req.params.cod);
        })

I tried to set a Custom Id, but none of these worked. Any idea what I can do?

    
asked by anonymous 25.05.2016 / 22:25

1 answer

1

Then your bank is fed ok in the format {cod: Number, city: String, name: String} ?? First step to be checked ..

For the little that I am studying so far your json should be treated since it is treating the fields "1", "2" as a compound field and you do not have the reference to cod and yes to fields 1, 2.

Ex:

mongoose-user-test> db.teste.find()
{
  "_id": ObjectId("57464d7729950798b4ad3d85"),
  "1": {
  "cidade": "cidade1",
  "name": "nome1"
},
 "2": {
"cidade": "cidade2",
"name": "nome2"
 }
}

Now if your json is formatted like this:

{"cod": "1","cidade":"cidade1","name":"nome1"}
{"cod":"2", "cidade":"cidade2", "name":"nome2"} 

If yes you can do a simple find:

My.find({cod: req.params.cod }, function(err, data){...});

Ex:

mongoose-user-test> db.teste.find()
{
  "_id": ObjectId("57464f5529950798b4ad3d86"),
  "cod": "2",
  "cidade": "cidade2",
  "name": "nome2"
}
{
  "_id": ObjectId("57464f5529950798b4ad3d87"),
  "cod": "1",
  "cidade": "cidade1",
  "name": "nome1"
}

mongoose-user-test> db.teste.find({cod:"2"})
{
  "_id": ObjectId("57464f5529950798b4ad3d86"),
  "cod": "2",
  "cidade": "cidade2",
  "name": "nome2"
}

Another thing to note is that it is treating all elements of your json as a string. Same in the above query if I did find with {cod: 2} no element would be returned.

    
26.05.2016 / 03:29