Nodejs: Moongoose can't find the object - node.js

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 }

Related

mongoose#populate returns null in nested object inside array

I have a mongoDB database which is generated using a script that uses only the node.js mongoDB driver without mongoose. Later on, in the application, I want to use mongoose to load a document and have a reference be populated automatically; however, this only ever returns null.
Imagine a task which contains sub-items which each have a title and an assigned person. The assigned person, in this case, is the reference I want to have populated, so the reference lives in an object inside an array in the task schema.
The following code (requiring npm install mongodb mongoose) reproduces the problem (watch out, it destroys a local database named test if you have one already):
const mongodb = require('mongodb');
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
(async () => {
// Step 1: Insert data. This is done using the mongodb driver without mongoose.
const db = await mongodb.MongoClient.connect('mongodb://localhost/test');
await db.dropDatabase();
await db.collection('persons').insertOne({ name: 'Joe' });
const joe = await db.collection('persons').findOne({ name: 'Joe' });
await db.collection('tasks').insertOne({ items: [{ title: 'Test', person: joe._id }] });
await db.close();
// ================
// Step 2: Create the schemas and models.
const PersonSchema = new Schema({
name: String,
});
const Person = mongoose.model('Person', PersonSchema);
const TaskSchema = new Schema({
items: [{
title: String,
person: { type: Schema.Types.ObjectId, ref: 'Person' },
}],
});
const Task = mongoose.model('Task', TaskSchema);
// ================
// Step 3: Try to query the task and have it populated.
mongoose.connect('mongodb://localhost/test');
mongoose.Promise = Promise;
const myTask = await Task.findOne({}).populate('items.person');
// :-( Unfortunately this prints only
// { _id: "594283a5957e327d4896d135", items: [ { title: 'Test', person: null } ] }
console.log(JSON.stringify(myTask, null, 4));
mongoose.connection.close();
})();
The expected output would be
{ _id: "594283a5957e327d4896d135", items: [ { title: 'Test', person: { _id: "594283a5957e327d4896d134", name: "Joe" } } ] }
I have verified that the two _ids actually match using mongo shell:
> db.persons.find({})
{ "_id" : ObjectId("594283a5957e327d4896d134"), "name" : "Joe" }
> db.tasks.find({})
{ "_id" : ObjectId("594283a5957e327d4896d135"), "items" : [ { "title" : "Test", "person" : ObjectId("594283a5957e327d4896d134") } ] }
What am I doing wrong when attempting to populate person? I am using mongoose 4.10.6 and mongodb 2.2.28.
The answer to this problem lies in the fact that the collection name mongoose automatically infers from the model Person is people and not persons.
The problem can be solved either by writing to the people collection in the first part or by forcing mongoose to use the collection name persons:
const Person = mongoose.model('Person', PersonSchema, 'persons');
mongoose plans to remove pluralization in the collection name anyway, see #1350 on Github.

mongoose find not fetching any result

I've simple collection in mongo and a corresponding mongoose model. This collection will only contain one document always. When I run a query in mongoshell it is giving me the result, but when I try to do findOne using mongoose it is not returning any result at all. Can someone help me figure out what is wrong. Below is my code.
Model:
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
lastResetMonth: {
type: Number
},
lastResetWeek: {
type: Number
},
currentFisYear:{
type: Number
}
});
module.exports = mongoose.model('ReserveResetTrack', schema, 'reserveResetTrack');
const ReserveResetTrack = require('../models/ReserveResetTrack');
ReserveResetTrack.findOne({})
.then(trackData => {
return {
lastFisMonth: trackData.lastMonth,
lastFisWeek: trackData.lastWeek
}
});
The above code is always returning nothing but a promise.
This is the only document i've in my collection and this will be the only one for ever
{
"_id" : ObjectId("589271a36bfa2da821b13ce8"),
"lastMonth" : 0,
"lastWeek" : 0,
"currentYear" : 0
}
Use exec() like this:
ReserveResetTrack.findOne({})
.exec() // <--- use exec() here
.then(trackData => {
return {
lastFisMonth: trackData.lastMonth,
lastFisWeek: trackData.lastWeek
}
});

MongoDB Query Returns Empty Array

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' });

How to use $in in mongoose reference schema

I have 2 schemas 1st is city and second is pincode. Pincode having reference of city. They both look like this
CITY schema
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
// create a all city list
var allCitySchema = new Schema({
cities: {
type: String
}
}, {collection: 'allcities'});
var allcities = mongoose.model('allcities', allCitySchema);
module.exports = allcities;
Pincode schemas
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var allPincode = new Schema({
city_id: {
type: Schema.ObjectId,
ref: 'allcities'
},
pincode: {
type: String
}
}, {collection: 'pincode'});
var allPincode = mongoose.model('pincode', allPincode);
module.exports = allPincode;
Now the problem is when i tried to fetch all pincode based upon city id for that i tries like this
app.post('/api/getPincodeByCity', function(req, res) {
console.log("In pincode");
var cities_id = [];
cities_id = req.body.cities_id;
console.log(req.body); // { cities_id: '["5597aa08c0a0beb40be128d4","5597aa2bbb18fefc142b6915"]' }
console.log(cities_id);
pincodes.findById( {city_id: { $in: cities_id }}, function(err,pincodeIds){
if(err) res.send(err.message);
res.send(pincodeIds);
res.end('{"success" : "Recieved Successfully", "status" : 200}');
});
});
But it's not working its giving me this error
Cast to ObjectId failed for value "[object Object]" at path "_id"
I also try with find() instead of findById() method but it giving me this error
undefined is not a function
The $in operator is not just "strictly" for querying arrays as that can be done with basically any operator for a singular value.
It's actually a "list of arguments" which evaluates to an $or condition, but with shorter syntax:
var idList = ["559e0dbd045ac712fa1f19fa","559e0dbe045ac712fa1f19fb"];
var pincode = mongoose.model('pincode');
pincode.find({ "city_id": { "$in": idList } },function(err,docs) {
// do something here
});
Which as mentioned is short form for this:
pincode.find(
{
"$or": [
{ "city_id": "559e0dbd045ac712fa1f19fa" },
{ "city_id": "559e0dbe045ac712fa1f19fb" }
]
},
function(err,docs) {
// do something here
}
)
You are getting an error because you are overwriting the "array" definition with a "string" which is what all "request" objects are unless parsed otherwise.
The other reason for the error is you are calling the wrong method. .findById() expects a single argument of the _id for the document. To query other fields use .findOne() or in this case .find() since an $in will possibly match more than one document.

mongoose not retrieving _id

I am trying to find a document from mongo, but the findOne() brings the document with an undefined _id field.
why?
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/school');
var Schema = mongoose.Schema;
var scoreSchema = new Schema({
type: String,
score: Number
});
var studentSchema = new Schema({
name: String,
scores: [scoreSchema]
});
var mod = mongoose.model('Student', studentSchema);
mod.findOne(function(err, stud) {
console.log('id:' + stud._id);
});
You need to pass something to find in your query. For example:
mod.findOne({name: 'John'}, function(err, stud) {
console.log('id:' + stud._id);
});
See here on how to make queries in Mongoose.
You're not querying anything, notice the {} before the callback.
mod.findOne({}, function(err, stud) {
console.log('id:' + stud._id);
});
You might want to have a look at the Mongoose documentation.

Resources