Filtering json data with schema attribute

Asked

Viewed 111 times

1

I have a JSON in this format:

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

and I need to filter the data of 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 attribute cod and not by the id generated by Mongoose in a way where I typed /my/1 and he would return to me

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

I tried several ways but 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 ways worked. Any idea what I can do?

1 answer

1


Then your bank is fed ok in the format {Cod: Number, city: String, name: String} ?? First step to check out..

For the little I am studying so far your json should be treated because it is treating the fields "1", "2" as compound field and you do not have the reference to Cod but 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 make 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 its json as string.. The same in the above query if I found {Cod:2} no element would be returned.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.