0

I'm trying to get a Mongoose scheme to perform point based $near finds. I'm just trying to obtain random documents and I'm getting guide from this answer.

I've tried:

    Video.where('randomTag').near({
        center: {
            type: 'Point',
            coordinates: [-98.18, 19]
        }
    }).exec(function (err, videos) {
        console.log(err)
        response.json(videos);
    })

Also:

    Video.near('randomTag',{
        center: {
            type: 'Point',
            coordinates: [-98.18, 19]
        }
    }).exec(function (err, videos) {
        console.log(err)
        response.json(videos);
    })

And:

    Video.find({
        randomTag: {
            $near: {
                $geometry: {
                    type: "Point",
                    coordinates: [Math.random()/Math.random(), 0]
                }
            }
        }
    }).exec(function (err,videos) {
        response.json(videos)
    })

And for all those attemps I got this error:

error: Can't use $near with Number.

I already got the required index:

{randomTag: '2dsphere'} 

The schema looks like:

{
  videoId: String,
  randomTab: Array(Number),
  title: String,
  playCount: Number
}

Here is some sample data.

{
    "videoId": "aRDAz55d-y",
    "randomTag": [2.255285185646381,0],
    "title": "La décima, inolvidable",
    "playCount": 254111
}

{
    "videoId": "vAFj32af",
    "randomTag": [0.4515513067517708,0],
    "title": "SILePetitPrince",
    "playCount": 900
}

This is whole error trace:

Error: Can't use $near with Number.
    at SchemaNumber.castForQuery (/storage/home/dev/final-cut/node_modules/mongoose/lib/schema/number.js:261:13)
    at module.exports (/storage/home/dev/final-cut/node_modules/mongoose/lib/cast.js:196:39)
    at Query.cast (/storage/home/dev/final-cut/node_modules/mongoose/lib/query.js:2341:10)
    at Query.find (/storage/home/dev/final-cut/node_modules/mongoose/lib/query.js:998:10)
    at Function.find (/storage/home/dev/final-cut/node_modules/mongoose/lib/model.js:1026:13)
    at sayHello (/storage/home/dev/final-cut/api/controllers/api.js:23:15)
    at Layer.handle [as handle_request] (/storage/home/dev/final-cut/node_modules/express/lib/router/layer.js:95:5)
    at next (/storage/home/dev/final-cut/node_modules/express/lib/router/route.js:131:13)
    at Route.dispatch (/storage/home/dev/final-cut/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/storage/home/dev/final-cut/node_modules/express/lib/router/layer.js:95:5)
    at /storage/home/dev/final-cut/node_modules/express/lib/router/index.js:277:22
    at Function.process_params (/storage/home/dev/final-cut/node_modules/express/lib/router/index.js:330:12)
    at next (/storage/home/dev/final-cut/node_modules/express/lib/router/index.js:271:10)
    at Function.handle (/storage/home/dev/final-cut/node_modules/express/lib/router/index.js:176:3)
    at router (/storage/home/dev/final-cut/node_modules/express/lib/router/index.js:46:12)
    at Layer.handle [as handle_request] (/storage/home/dev/final-cut/node_modules/express/lib/router/layer.js:95:5)
GET /api/hello 500 20.560 ms - -

The reason of the Math.random() use is because of the randomness need. Is there something I'm missing?

Community
  • 1
  • 1
diegoaguilar
  • 8,179
  • 14
  • 80
  • 129
  • Why are you calling `Math.random()` here? And also note that your other array attempts are "Strings". Use coordinates `[-98.18, 19]` without any string quotes instead. And what does your model look like? You likely have it defined wrong, and especially if you are trying to match strings then your documents are likely incorrect as well. – Blakes Seven Oct 21 '15 at 09:42
  • I've edited my answer telling why `Math.random()`. About the *string arrays* it was a last dummy type I did at last but I was actually trying with actual arrays. – diegoaguilar Oct 21 '15 at 09:46
  • You need to understand that "Random" is pretty random and unlikely to be "near" anything you really have stored unless you are looking for random numbers in a specific range. I'd also like to see some sample data you expect to match as well as your mongoose model as there is likely some problem in one or both as well. `Math.random` generates a floating point value in between `0` and `1`, so you certainly don't want that the way you are using it. You added a schema but there is either a typo or your field name `ramdomTab` is incorrect. – Blakes Seven Oct 21 '15 at 09:49
  • I provided to example records in my last edit. Well so far the problem is the actual `Error` being returned by the query function. – diegoaguilar Oct 21 '15 at 09:54

1 Answers1

1

Looks good to me. You must be doing something different to this listing:

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

var videoSchema = new Schema({
  videoId: String,
  randomTag: [Number],
  title: String,
  playCount: Number
});

videoSchema.index({ "randomTag": "2dsphere" });

var Video = mongoose.model( 'Video', videoSchema );

mongoose.connect('mongodb://localhost/test');

mongoose.set("debug",true);

Video.find(
  {
    "randomTag": {
      "$near": {
        "$geometry": {
          "type": "Point",
          "coordinates": [Math.random()/Math.random(),0]
        }
      }
    }
  },
  function(err,videos) {
    if (err) throw err;
    console.log(videos);
    mongoose.disconnect();
  }
);

Which gives me results like this:

Mongoose: videos.ensureIndex({ randomTag: '2dsphere' }) { background: true }
Mongoose: videos.find({ randomTag: { '$near': { '$geometry': { type: 'Point', coordinates: [ 1.8434117849022023, '\u001b[33m0\u001b[39m' ] } } } }) { fields: undefined }
[ { playCount: 254111,
    title: 'La décima, inolvidable',
    randomTag: [ 2.255285185646381, 0 ],
    videoId: 'aRDAz55d-y',
    _id: 5627616d76dfa5adcd39fd38 },
  { playCount: 900,
    title: 'SILePetitPrince',
    randomTag: [ 0.4515513067517708, 0 ],
    videoId: 'vAFj32af',
    _id: 5627616d76dfa5adcd39fd39 } ]
Blakes Seven
  • 49,422
  • 14
  • 129
  • 135
  • I've *replicated code you suggest*, I'm still getting the error, I'm updating and posting the error being thrown. – diegoaguilar Oct 21 '15 at 21:39
  • @diegoaguilar Which mongoose version are you using here? Try and bump it to a newer version ( at least for a standalone test ), as this works fine on 4.1.12 Use `npm list` if you are not sure. – Blakes Seven Oct 22 '15 at 03:52
  • 1
    @diegoaguilar Create a new project folder just for the listing here and run it as is and you will see it work. These things are usually caused by dependency problems in your current project or inclusion of other plugins that are causing the conflict. You generally resolve those by starting with the raw things you only need and then adding other things until it breaks. – Blakes Seven Oct 23 '15 at 05:06