Converting object returned by MongoDB into bar? - node.js

I think this is a very simple question? I am a beginner trying to learn mongo with node.
Once I have saved something to a collection, how can I pull it out in simple var format?
db.highschools.save({
hsid :10,
name :"Johnson High School",
location:"San Diego, CA"
});
I simply want to store a var as 'Johnson High School'.
My failed attempts that have returned undefined are as follows...
var hsName = db.highschools.find({hsid:10}).name;
var hsName = db.highschools.find({hsid:10}).name.str;
Pretty sure I'm missing the big picture here, would someone please be kind enough to help me figure this out?

Use findOne instead:
var hsName = db.highschools.findOne({hsid:10}).name;
Also, note that this is a Mongo script, not a NodeJS script.

You'll need to make it async when you write the logic in NodeJS.
db.collection('students', function(err, collection) {
collection.findOne({hsid:10}, function(err, student) {
if (err) { throw err; }
console.log(student.name);
});
});
If you're confident that there should be only one result, then you can use the shortcut method findOne which simply calls find internally with a limit of one. If you were to use find, it returns an array of matches.

Related

Node Js MongoDB Query Against returned array

I have a mongodb Relationships collection that stores the user_id and the followee_id(person the user is following). If I query for against the user_id I can find all the the individuals the user is following. Next I need to query the Users collection against all of the returned followee ids to get their personal information. This is where I confused. How would I accomplish this?
NOTE: I know I can embed the followees in the individual user's document and use and $in operator but I do not want to go this route. I want to maintain the most flexibility I can.
You can use an $in query without denormalizing the followees on the user. You just need to do a little bit of data manipulation:
Relationship.find({user_id: user_id}, function(error, relationships) {
var followee_ids = relationships.map(function(relationship) {
return relationship.followee_id;
});
User.find({_id: { $in: followee_ids}}, function(error, users) {
// voila
});
};
if i got your problem right(i think so).
you need to query each of the "individuals the user is following".
that means to query the database multiple queries about each one and get the data.
because the queries in node.js (i assume you using mongoose) are asynchronies you need to get your code more asynchronies for this task.
if you not familier with the async module in node.js it's about time to know it.
see npm async for docs.
i made you a sample code for your query and how it needs to be.
/*array of followee_id from the last query*/
function query(followee_id_arr, callback) {
var async = require('async')
var allResults = [];
async.eachSerias(followee_id_arr, function (f_id, callback){
db.userCollection.findOne({_id : f_id},{_id : 1, personalData : 1},function(err, data){
if(err) {/*handel error*/}
else {
allResults.push(data);
callback()
}
}, function(){
callback(null, allResults);
})
})
}
you can even make all the queries in parallel (for better preformance) by using async.map

mongodb async issue NodeJS

I'm using mongodb for a while and had countered this same issue many times.. like so:
XCollection.find({})
.each(function (err, x) {
if (err) throw err;
branchCollection.findOne(
{_id: new ObjectID(x.branchId)}
, function(err, doc){
console.log(x.branchId);
});
.....
and I see sometimes that findOne not working very well, x document changes because of the upper each, and that's affecting my code! I recognize that the problem is because those requests (db requests) is async. but what the recommended method to deal with this issue?
Thanks,
Best Regards
You do not need to use new ObjectID to query the ID field. A string will suffice.
branchCollection.findOne(
{_id: x.branchId}
, function(err, doc){
console.log(doc._id);
});
On another note, you should not be using the x variable in your async call. You should use:
console.log(doc._id)
Other than that, I'm not sure I understand what your question is? Are you receiving an error?

Update not working-NodeJs and MongoDB using MongoClient

I was going through the mongodb and nodejs course on MongoDBUniversity and one of the task involves finding the documents which has the highest recorded temperature for any state and then add a field "month_high" to it.I am able to find the documents for the state with the highest temperature but am unable to update it. The code is as below.
Can someone tell me what might I be doing wrong?
var MongoClient=require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/course',function(err,db){
var cursor=db.collection("weather").find();
cursor.sort({"State":1,"Temperature":-1});
var oldState,newState;
cursor.each(function(err,doc){
if(err)throw err;
if(doc==null){
return db.close();
}
newState=doc.State;
if(newState!=oldState){
var operator={'$set':{"month_high":true}};
var query={"_id":doc._id};
console.log(doc._id+" has temp "+doc.Temperature+" "+doc.State);
db.collection("weather").update(doc,operator,function(err,updated){
console.log("hi");//---->Never Logs
if(err)throw err;
// console.log(JSON.stringify(updated));
})
}
oldState=newState;
});
});
I'm not 100% sure, but given the syntax reported on the docs you might have to specify the options parameter even if not using it:
db.collection("weather").update(doc,operator, options, function(err,updated)
Also, the connection might get closed before the callbacks are called. Does it change anything if you remove the db.close() call?
Collection name is 'data'. In this homework 'weather' is database name.
See
https://education.mongodb.com/courses/10gen/M101JS/2013_October/courseware/CRUD/Homework_2.2/
> use weather
switched to db weather
> db.data.findOne()

MongoDB on Node.js doesn't work, it returns undefined

In the following code:
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect('mongodb://localhost:27017/db_name', function(err, db){
if (err) throw err;
var collection = db.collection('col_name');
console.log(collection.find().toArray(function(err, items){}));
});
When I run the above, it doesn't return any results and instead returns undefined. What am I missing?
Also, in order to confirm there exist some collections on the db, which there are, I tried to add console.log(db.getCollectionNames());, but it looks like it has no such method in Node.js driver. So is it still possible to confirm the existence of collections? (Anyway I just want to use it as debug in these situations - usually I don't need the method though).
Thanks.
Don't log your entire find() function, do the checking in the callback:
collection.find().toArray(function(err, items){
console.log(items);
});
For the getCollectionNames() part, the method is actually called collectionNames() in the mongodb native driver :
db.collectionNames(function (err, list) {console.log(list)});

Confused about node-mongodb-native syntax

I'm just getting into node and mongodb and came across the first obstacle.
I'm walking through a tutorial where the code looks something like this:
var db = new mongo.Db("database", new mongo.Server(host, port, {}));
db.open(function(error){
db.collection("user", function(err, collection){
collection.find({"id":"1"}, function(error, cursor){
cursor.toArray(function(err, users){
if(users.length == 0){
console.log("no such user");
} else if {
console.log("user found: ", users[0]);
}
});
});
});
However the code failed to work saying that users is null. (I do have a code where it inserts entries) Anyway, while trying to figure out what's going on, I've come across the documentation where it uses a synchronous pattern for find instead of using callback to retrieve cursor. The code goes something like this:
var cursor = collection.find({"id":"1"});
In fact, I cannot find anywhere in the documentation where it mentions a usage of find with a callback that returns a cursor. I am really confused. Is the tutorial outdated? And what is wrong with this code?
If users is null, then it's likely that err is indicating what the problem is. Add an if (err) path to your code to log err when it's set.
find can work in both ways that you describe. The callback parameter is optional and if you don't provide it you can use the cursor that's returned instead. See the docs: link.

Resources