MongoDB findById not working - javascript

I'm using Monk and MongoDB to try and get a record by ID populate through the request params but it returns nothing.
I've tried lots of the suggestions on SO but nothing is working, does anyone have any ideas where I'm going wrong?
Here is my code:
router.get('/:id', function(req, res) {
var db = req.db;
var collection = db.get('bugs');
collection.findById(req.params.id, {}, function(e,docs){
res.render('bug', { 'bug': docs });
});
});
And I'm trying to access by going to localhost:3000/bugs/recordidstring
Thanks

I was being an utter idiot and when I was connecting to the DB I was connecting to the wrong one!
Sorry guys, my bad!

Related

Problem extracting data from NEDB database Node.JS

I have a NEDB Datastore called users which contains one line of information. I call a fetch request to retrieve the users from the server and I can tell that the request is being processed by debugging. However, the users.find() is not working and I have no idea why. When I tried the same code with an alternate datastore, it worked fine.
Here is my Javascript code:
//Client side JS
async function extractUsers() {
const userJ = await fetch('/getUser');
let user = await userJ.json();
header.innerHTML = "Welcome " + user + "!";
}
//Server Side JS
const users = new Datastore('users.db');
users.loadDatabase();
app.get('/getUser', (req, res) => {
users.find({}, (err, data) => {
res.json(data);
})
});
If you have any idea why this is happening or need more information, please let me know. Thanks!
I simply deleted the users.db file and restarted the server, manually re-entering the data and it seemed to work.

Mongo Error: Duplicate Key error makes no sense

Hi fellow developers!
I've got this error showing up in my console when I try to save two identical documents in a collection in MongoDB that has nothing to do with the index shown in the error.
Here's the error: E11000 duplicate key error collection: Bohemian.orders index: user.email_1 dup key: { user.email: null }
Now this makes no sense, because I'm trying to save an Order document in a separate collection, which has nothing to do with the user router I had set up previously.
Here is the schema and model code:
const mongoose = require('mongoose');
const orderSchema = new mongoose.Schema({
amountToPay: Number,
});
const Order = mongoose.model("Order", orderSchema);
module.exports.Order = Order;
As shown here, I am only trying to save the amount to be payed into the database in a separate collection.
Here is the router file:
const express = require('express');
const router = express.Router();
const { Order } = require('../models/Order');
router.get("/", async (req, res, next) => {
try {
const orders = await Order.find();
if (orders.length === 0) return res.status(404).send("There are currently no orders");
res.send(orders);
} catch (ex) {
console.error(ex);
next();
}
});
router.post("/", async (req, res, next) => {
try {
const order = new Order({
amountToPay: req.body.amountToPay
});
await order.save();
res.send(order);
} catch (ex) {
console.error(ex);
next();
}
});
module.exports = router;
As you can see there is nothing relative to the error that I'm getting and I have no clue why I'm getting a duplicate user.email = null key , when I haven't made any reference to the User model or router.
Here is the POST call I'm making from POSTMAN to test:
Pretty straight forward, nothing extreme, nothing tangled, right? Well the first ever POST call saves the document in the Database, but from then on I keep getting the same error. The only thing I can take from that is that when I save the first document, Mongo looks for the user.email property when I'm creating the new instance of Order and when it doesnt find it, it creates it with a value of null and then the next document would naturally be a duplicate, hence the error. But I'm confused, because this model and router should not absolutely nothing to do with the user ones.
Here is the error:
So please if anyone can help me understand why MongoDB is screwing with me or where I'm making a mistake, I would really appreciate it.
I found out what the problems was, thanks to Molda:
At some point I had created these indexes, which I'm still unsure when and how, but I did. Which essentially lead to this error, when I tried to save the second document.
A simple quick console log of the indexes in the collection showed that I had that index in there.
const indexes = await Order.collection.getIndexes();
console.log(indexes);
Then I removed them using this method:
await Order.collection.dropIndexes("user.email_1");
And everything worked flawlessly from there.
I hope this helps anyone in this situation in the future and thanks Molda! :)

How to create URL for every MongoDB document

I'm trying to map a URL using express routes to a specific value from every document I have in the database.
For example. In the Schema company.name would return a company name.
Is there a way to set the value of company.name to a unique URL?
The only way I thought of it was creating a loop or using mongoose's .find to iterate through the database and set it to
app.get('/' + name , function (req , res ) {
res.render('company.jade');
});
However I'm not sure how to access the database collections from the routes file.
Using
const Company = require('.models/company');
Doesn't return the database so not sure what to do.
I'm not really hip on Mongoose or node.js yet. Really only need to do this one thing and the rest of the app is done in angular which I'm more familiar with.
Hopefully I made some sense here. I do have code for the app buts it's all basic code from app.js and routes.js. I can add it if it would be helpful.
You are looking for Mongoose findOne query.
const Company = require('.models/company');
app.get('/:name', function(req, res){
Company.findOne({'company.name': req.params.name}) //company.name depends upon the schema you set.
.then(function(company){
if (company)
return res.send({success: true, data: company}); //return company as an object containing the queried company document.
else
return res.send({success: false, error: 'Company not found'});
})
.catch(function(err){
if (err) res.send({success: false, error: err});
});
});

MongoDB: Find function not working in JS file

On my localhost/list page, my GET is showing
[{"_id":"5756f1aa64fa4d3104f98f89","mcr":"relationship","info":{"test":"test"}}]
but I would like to only return
[{"info":{"test":"test"}}]
My find function works just fine on the mongo command line and it returns what is expected.:
db.usercollection.find({},{"_id":0,"mcr":0})
However, when called in my JS file, it doesn't filter out the query. I'm using express and monk along with MongoDB. This is my router.get:
router.get('/list', function(req, res) {
var db = req.db;
var collection = db.get('usercollection');
collection.find({},{"_id":0,"mcr":0},function(e,docs){
res.json(docs);
});
});
No errors are thrown and the status code is 200, what could the problem be? I've tried a ton of variations within the find function, and haven't had any luck.
I found the issue, apparently mongo hadn't updated their docs completely. I needed to use {fields: {_id:0}}.
Final code:
router.get('/list', function(req, res) {
req.db.get('usercollection').find({},{fields: {"_id":0,"mcr":0}},function(e,docs){
res.json(docs);
//console.log(docs);
});
});

Mongo collection has no .find method

I have a database on MongoLab. It has several collections. All but one work. One collection is called "selectopts". It has two documents. I can clearly see these two documents.
In my express code I have...
var db = require('mongojs');
db.connect('mongodb://xxxx:xxxx#ds053xxx.mongolab.com:53xxx/rednecks',['selectopts']);
exports.selects = function (req, res) {
db.selectopts.find(function (err, s) {
if (err) return;
res.json(s);
});
};
It always errors at db.selectopts.find..., TypeError: Cannot call method 'find' of undefined. This exact same stupid simple code works fine for four other collections. Why is just this one collection not coming back from MongoLab?
I'm so completely stumped.
EDIT...
Tried db.collection('selectopts').find(... and got this error...
EDIT again...
Here are the two docs in the selectopts collection on MongoLab. Do you see some problem with the docs?...
EDIT x 3...
This is the correct/working mongo connection setup code...
var mongojs = require('mongojs');
var db = mongojs.connect(
'xxx:xxx#ds053xxx.mongolab.com:53xxx/rednecks',
);
See the main difference? (SMFH) :-/
Sometimes when I post at SO I don't receive the exact actual answer from any one reply, but somehow you guys always steer me toward the answer. In this case, it was programmer stupidity. My code at the top of the route js file is wrong. You can see it wrong at the top of this post. I edited and added the correct syntax, which magically got everything working.
To eliminate this type of repetition/syntax/non-DRY bungling, I moved the mongo connection lines into a separate database.js file and require it at the top of the route files. Genius huh?!? :-D
"Thank you" x 100 for all your replies! You always get me back on track :-)
Connect using the following style:
var MongoClient = require('mongodb').MongoClient;
var db;
MongoClient.connect(
'mongodb://xxxx:xxxx#ds053xxx.mongolab.com:53xxx/rednecks',
{auto_reconnect: true},
function(e, database)
{
db = database;
});
exports.selects = function (req, res) {
db.selectopts.find(function (err, s) {
if (err) return;
res.json(s);
});
};

Categories

Resources