Working in the same office as this guy helps a lot. The problem he was facing was that he had mapped 2 different handlers to a single route. With no distinction between them, his string George
was being passed to the mongojs.ObjectId
builder as part of the findOne
call and that was generating the Argument passed in must be a single String of 12 bytes or a string of 24 hex characters
error message. Updating the routes so that they were distinct solved the problem.
MongoDB mongojs node
Question
I'm trying to learn node, mongodb and mongojs and have a newbie question.
My route looks like this ...
server.get({path: PATH + '/:author', version: '0.0.1'}, msg.findMsgsByAuthor);
My JSON looks like this ...
{
"parentId": "1234",
"category": 1,
"author": "George",
"title": "Threaded Messages",
"body": "blah blah blah blah",
"likes": "5",
"dislikes": "10",
"inaccurate": "20"
}
What I want to do would be simple in SQL -- select * from msgs where author = 'George'
How do I do this using mongo/mongojs?
I've tried something like this with no success...
msgs.find({author: req.params.author}, function (err, success) { ...}
The callback code is
exports.findMsgsByAuthor = function (req, res, next) {
res.setHeader('Access-Control-Allow-Origin', '*');
msgs.find({author: req.params.author}).sort({category: 1}, function (err, success) {
logit(err, success);
if (success) {
res.send(200, success);
return next();
}
return next(err);
})
};
Here are some declarations
var msgs = require('../setup').msgs;
var mongojs = require('../setup').mongojs;
var db = require('../setup').db;
And setup.js is
var config = require('./config');
var connection_string = config.connectionString;
var mongojs = exports.mongojs = require('mongojs');
var db = exports.db = mongojs(connection_string, ['msg', 'user']);
var msgs = exports.msgs = db.collection("msgs");
var port = exports.port = config.port;
var ipAddress = exports.ipAddress = config.ipAddress;
And lastly, config.json
{
"connectionString":"127.0.0.1:27017/msg",
"ipAddress":"127.0.0.1",
"port": "8080"
}
When I say the code is not working, I mean that when I test using the Postman Rest Client Chrome plug in I get the following
{
"code": "InternalError",
"message": "Argument passed in must be a single String of 12 bytes or a string of 24 hex characters"
}
When I attempt a GET with
http://127.0.0.1:8080/msgs/George
If I use a similar callback using msgs.findOne, it works as expected
msgs.findOne({_id: mongojs.ObjectId(req.params.msgId)}, function (err, success) {...}
I think that should be enough code to explain what I'm trying to do
Any guidance would be appreciated.
Solution
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow