我有一个问题,希望有人可以帮助我。我正在尝试创建一个应用程序,它将使用mongodb从一个点搜索半径范围内的人。我已经在本地mongodb上完成了它并且它可以工作但是当我尝试使用node.js并且去Heroku时它不起作用。我可以将每个示例数据发布到数据库中,没有任何问题。我可以看到索引是在数据库上创建的。我可以根据名字进行查找。由于某种原因,我不能靠近$。这是我想要做的:
示例数据:
{
"name":"Frank",
"loc": {"lon": 51, "lat": -114}
}
{
"name":"Jim",
"loc": {"lon": 151, "lat": 114}
}
在我使用的Server.JS中:
var express = require("express");
var bodyParser = require("body-parser");
var mongodb = require("mongodb");
var ObjectID = mongodb.ObjectID;
var GEO_LOC = "geoloc";
var app = express();
app.use(bodyParser.json());
// Create a database variable outside of the database connection callback to reuse the connection pool in the app.
var db;
//Connect to the database before starting the application server.
mongodb.MongoClient.connect(process.env.MONGODB_URI, function (err, database) {
if (err) {
console.log(err);
process.exit(1);
}
//Save database object from the callback for reuse.
db = database;
console.log("Database connection ready");
//Initialize the app.
var server = app.listen(process.env.PORT || 8080, function () {
var port = server.address().port;
console.log("App now running on port", port);
});
});
//API ROUTES BELOW
// Generic error handler use by all endpoints.
function handleError(res, reason, message, code) {
console.log("ERROR: " + reason);
res.status(code || 500).json({"error": message});
}
app.post("/api/setgeo", function(req, res) {
var newRL = req.body;
db.collection(GEO_LOC).insertOne(newRL, function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to create.");
} else {
res.status(201).json(doc.ops[0]);
}
});
db.collection(GEO_LOC).ensureIndex({"loc": "2d"});
});
app.get("/api/getname", function(req, res) {
var findQuery = "{";
if (req.query.name) {
findQuery = findQuery + " \"name\": \"" + req.query.name + "\"}";
}
db.collection(RESPONDER_LOCATION_COLLECTION).find(JSON.parse(findQuery)).toArray(function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get information");
} else {
res.status(200).json(doc);
}
});
});
app.get("/api/getgeo", function(req, res) {
var findQuery = "{\"loc\": {$near:[51, -113]";}}";
db.collection(RESPONDER_LOCATION_COLLECTION).find(JSON.parse(findQuery)).toArray(function(err, doc) {
if (err) {
handleError(res, err.message, "Failed to get information");
} else {
res.status(200).json(doc);
}
});
});