MongoDB Query Returns Empty Array - node.js

Have a basic express app going that is connected to an almost .5 GB MongoDB Database...When I run:
router.get('/', function(req, res, next) {
medical_data.find({'State':'CT'}, function(err, data) {
console.log(data)
res.render('index');
});
});
I get a blank array returned:
[]
GET / 304 87.233 ms - -
GET /stylesheets/style.css 304 4.842 ms - -
Here is the entry from MongoLab that I'm trying to query for:
{
"_id": {
"$oid": "5671dfafd7f6fdd02436682e"
},
"Street": "65 KANE ST",
"City": "WEST HARTFORD",
"State": "CT"
}
And here is my medical_data model:
var mongoose = require('mongoose');
var medical_data_schema = new mongoose.Schema({
Street: String,
City: String,
State: String
});
var medical_data = mongoose.model('medical_data', medical_data_schema);
// Make this available to our other files
module.exports = medical_data;
Why am I getting a blank array back? If I run findOne instead of find I get null in the console
I've run other succesfull node apps before but none with a database as big as this, so I think it might be a timeout issue? I'm not sure, any help would be amazing.

Fitting a Mongoose schema on top of an existing database can be tricky. For one, Mongoose will determine the collection name by pluralizing the model name; so in your case, Mongoose will use the collection medical_datas, and my guess is that it's actually called medical_data.
You can specify the collection name to use for a schema by using the collection option:
var medical_data_schema = new mongoose.Schema({
Street : String,
City : String,
State : String
}, { collection : 'medical_data' });

Related

How to get latest object of array from users in Mongodb

my mongodb structure
//First user
_id:ObjectId("12345")
name:"prudhvi"
authors:Array
0:Object
authorId:"77777"
authortitle:"medicine"
1:Object
authorId:"66666"
authortitle:"Hospital"
//second user
_id:ObjectId("67890")
name:"venkat"
authors:Array
0:Object
authorId:"55555"
authortitle:"Doctor"
1:Object
authorId:"44444"
authortitle:"Nurse"
Can someone please help here i have two users, On that i need to get only the latest object of authors array. Here my latest Object is 1:Object, If in case one more is added, I need to get 2:Object of data of all users.
I tried like this but i am getting all objects of authors array, But i need to get latest object
userRouter.post('/getAuthors', function (req, res) {
Collections.user.find(req.body.user, function (err, result) {
if (err) res.status(500).send("There was a problem finding the user");
if (result.length > 0) {
res.status(200).send(result[0].authors);
}
}).select({ "authors": 1 });
});
Try using this
Collections.user.find().limit(1).sort({$natural:-1})
Take a look at $natural and cursor.sort
In your mongoose schema you can set timestamps. it will automatically set createdAt time stamp when you create a object from that schema and if you edit that particular object it set updatedAt timestamp.
As a example schema,
const mongoose = require('mongoose');
const markSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
mark: { type: Number },
student: { type: String },
},{
timestamps: true
});
module.exports = mongoose.model('Mark', markSchema);
like this you can set timestamps.

No Data in Mongo

Using Mongoose in NodeJS I'm able to create a database and insert data and find the data when using mongoose, however when I use the mongo shell with show dbs command it shows the database but the size of the database constantly remains at 0. Is there something I'm missing? Here's my code
mongoose = require('mongoose');
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/dt');
var UserSchema = new Schema({
first_name: String,
last_name: String
});
var users = mongoose.model('Users',UserSchema);
var new_user = new users({ first_name: "firstname",
last_name: "lastname" });
new_user.save(function(err) {
if(err) return;
else console.log("saved");
});
users.find({first_name:'firstname'}).exec(function(err,data) {
console.log(data);
});
you might need to use the insert() method
e.g
db.detail.insert(
{
"data" : {
"name" : "any_name",
"zipcode" : "10075",
},
}
)
After which you can use the find() method returns query results in a cursor, which is an iterable object that yields documents.
You can read more from Insert a Document and Find or Query Data with the mongo Shell

Cannot read from database using mongoose

This is my GET request
var Catalog = mongoose.model('Catalog');
router.get('/catalog', function(req, res, next) {
Catalog.find(function(err, items){
if(err){
return next(err);
}
console.log(items);
res.json(items);
});
});
The model
var mongoose = require('mongoose');
var CatalogSchema = new mongoose.Schema({
title: String,
cost: String,
description: String
});
mongoose.model('Catalog', CatalogSchema);
The console.log gives me a [] but there is a collection named Catalog with the parameters filled.
If you have an existing collection, created outside of Mongoose, that you wish to query you need to configure your model to use that collection.
Otherwise, Mongoose will use a utility function to create a collection name by pluralizing and lowercasing the model name (which in your case would become catalogs).
To use Catalog as a collection, use the collection option:
var CatalogSchema = new mongoose.Schema({
title: String,
cost: String,
description: String
}, { collection : 'Catalog' });
you might check again the collection name in mongodb i.e whether it is 'Catalog' or 'Catalogs'. In my experience I found that if you name the model 'Catalog', then either mongoose creates the collection with a name 'Catalogs' if it is not already there or you have to create the collection first with a name 'Catalogs'.
You might check the following line also:
Catalog.find({}, function(err, items){
// your code goes here
}
Hope it helps..

Nodejs: Moongoose can't find the object

So I have a mongodb on mongolabs that looks something like this:
under the collection "news"
[{
"_id": {
"$oid": "542aab88e4b0e67da1edd1bd"
},
"year": 2014,
"data": {
"someinfo":"cool info"
}
}]
And on node I have the following:
//dependencies
var mongoose = require("mongoose");
var Schema = mongoose.Schema;
//Setting up the schemas
var newsSchema = new Schema({
year: String,
data: Object
});
mongoose.model('news',newsSchema);
//routes
var mongolabs = express.Router();
mongolabs.route('/List/:type1/:year')
.get(function(req, res){
mongoose.model(req.params.type1).find({year:req.params.year}, function(err,suc) {
res.jsonp(suc);
});
});
app.use('/mongo', mongolabs);
unfortunately when I go http:///mongo/List/news/2014, it returns empty.
I already tried everything I can think of, needless to say I am a newbie to mongoose, node and mongodb.
You're trying to query for a number value with a string value, hence the empty results.
Try casting the req.params.years as a number by adding the unary plus before your param.
{ year: +req.params.year }
You also could use the parseInt() function:
var year = parseInt(req.params.years, 10);
Probably you're passing null to the .find() method.
You're doing this:
{ year: req.params.type1.year }
,when you should be doing:
{ year: req.params.year }

MongooseJS using find to find by reference

I have this Mongoose Schema.
var mongoose = require('mongoose')
, dev = require('../db').dev();
var schema = new mongoose.Schema({
date: {
type: Date,
default: Date.now()
},
company: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Company'
},
questionnaire: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Questionnaire'
}
});
module.exports = dev.model('Survey', schema);
I want to find only the surveys which have a specific company id. How do I do that? I tried (with my Express handler):
app.get('/survey', function(req, res) {
Survey.find({ company: req.query.company })
.populate('questionnaire')
.exec(function(err, surveys) {
return res.json(surveys);
});
});
In your latest comment you say that the company field of the Surveys collection is actually a string and not and ObjectId and that's why this isn't working. Because your schema definition declares company as an ObjectId, Mongoose will cast your req.query.company value to an ObjectId and then query for documents in Surveys where their company property is an ObjectId with the same value. So if company is a string in the database it won't match.
If you update the company values in Surveys to be ObjectIds instead of strings then this will work.
have you tried 'company._id
app.get ('/survey', function (req, res) {
Survey.find ({ 'company._id': req.query.company }).populate ('questionnaire').exec (function (err, surveys) {
return res.json (surveys);
});
});
What worked for me (and it is hinted in the accepted answer) was to make sure that the documents are created through mongoose (i.e through your express server) because this will force the schema onto them, and thus the ids will be stored as objectIds.
Initially I had created a document manually through the database using the objectIds as simple strings, and this causes the query not to work because mongo casts the id (from your server) as an ObjectId.

Resources