getting specific item from query answer mongodb node - node.js

I was wondering if there is a way I can get a part of an object in mongo using node. For example, it would be great if I could log say the email that is being added, by using something like console.log(result.email) to get the email part of my response. Does anyone know how to do this?

Ok so I have found a way to do this. It will not work on the .find function for some reason, but will work on .findOne and .sort
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("db");
let query = {
username: "username",
key: "key"
};
dbo.collection("keys").findOne(query, (function(err, result) {
var lengthboi = result.length;
console.log(result)
if (lengthboi === 1) {
//do stuff
} else {
}
}));
});

Related

native js how to find a field name of a collection where another field equal to certain value

I know that on robomongo if I want to find _id of user where username = test2 I can use
db.getCollection('user').find({},{_id:1},{"username":"test2"})
now, on visual studio code, I want to find value of field "disabled" from user collection where field "username" value equal to variable "tempusername" value. I tried:
colUser = mongoDb.collection("user");
var status = colUser.find({},
{ disabled:1},{ username:tempusername},function (err, doc) {
console.log(doc);
});
but it shows value of status is "undefined". What is the write code for this?
I think it's something you're looking for.
const url = 'mongodb://localhost:27017'
MongoClient.connect(url, (err, db) => {
const dbo = db.db('mydb')
dbo.collection('user').find({disabled:'1',username:tempusername}).toArray((err, doc) => {
if(err){
console.log(err)
}
console.log(doc)
db.close()
})
})
I found the answer, basically the way it work is the result will be return inside the function, so I have to put it like this:
var statusbuffer;
colUser.findOne({ username:tempusername},{ _id:0,disabled:1},function (err, userstatus){
// User result only available inside of this function!
if (err) {
next("Failed to update records");
} else {
console.log("disabled status here:",userstatus.disabled) // => yields your user results
statusbuffer = userstatus.disabled;
next();
}
});
thanks all for your comments!

Show entire MongoDB contents in Node.js API

First off, don't worry, it's a tiny data set - I realise it wouldn't be wise to dump an entire production DB to a single screen via an API... I just need to get a JSON dump of entire (small) DB to return via an API endpoint in a Node.js application.
My application does successfully return single records with this code:
MongoClient.connect("mongodb://localhost:27017/search", function (err, db) {
if(err) throw err;
db.collection('results', function(err, collection) {
// search for match that "begins with" searchterm
collection.findOne({'string':new RegExp('^' + searchterm, 'i')}, function(err, items){
// get result
var result;
if (items == null || items.result == null){
result = "";
}
else {
result = items.result;
}
// return result
res.send(result);
});
});
});
So I know Node is talking to Mongo successfully, but how can I tweak this query/code to basically return what you get when you execute the following on the MongoDB command line:
$ db.results.find()
This is snippet.
model.find({}).exec(function (err, result) {
if (err) {console.error(err); return;}
else return result;
});
First use your predefined model and call find. the logic is to place a empty object {} essentially rendering . select all from this model.
Make sense?
Exactly as you've described it.
collection.find({}).exec((err, result) => {
if (err) {
console.log(err);
return;
}
if (result.length > 0) {
// We check that the length is > 0 because using .find() will always
// return an array, even an empty one. So just checking if it exists
// will yield a false positive
res.send(result);
// Could also just use `return result;`
});
Thanks guys, I appreciate your answers pointing me in the right direction, in terms of using {} as the query. Here is the code that eventually worked for me:
db.collection('results', function(err, collection) {
collection.find({}).toArray(function(err, docs) {
res.send(docs);
});
});
The crucial element being the toArray(...) part.

Storing Collection result from mongoDB in Node

I am new to node and I have read the data from mongoDB successfully.
But I would like to store the whole data from the Collection into a variable in nodejs as I would like to use them in the index page.
I do not know how to store it.
// Connection URL
var url = 'mongodb://localhost:27017/test';
// Use connect method to connect to the Server
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
console.log("Connected correctly to server");
seriescollection = db.collection('series');
});
var findseries = function (db, callback) {
var cursor = db.collection('series').find();
cursor.each(function (err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
} else {
callback();
}
});
};
MongoClient.connect(url, function (err, db) {
assert.equal(null, err);
//insertDocument(db, function () {});
findseries(db, function () {
db.close();
});
});
My sample JSON object in MongoDb is
{
"_id" : "b835225ba18",
"title" : "Name",
"imageurl" :"https://promotions.bellaliant.net/files/Images/TMN/Ballers-June2015.jpg",
"namespaceId" : "UNI890"
}
I would like to access all the fields and create a page based on the fields that I have stored. I need to access all the fields and that is my main goal.
This is a pet project I am working on a leisure time to learn MEAN stack a bit.
Thanks a lot for your help!!!!
There's a few issues with this code, but I think what you're looking for is the toArray method:
var findseries = function (db, callback) {
db.collection('series').find().toArray(function(err, allTheThings) {
// Do whatever with the array
// Spit them all out to console
console.log(allTheThings);
// Get the first one
allTheThings[0];
// Iterate over them
allTheThings.forEach(function(thing) {
// This is a single instance of thing
thing;
});
// Return them
callback(null, allTheThings);
}
}
More here: https://docs.mongodb.org/manual/reference/method/cursor.toArray/
And here: https://mongodb.github.io/node-mongodb-native/api-generated/cursor.html#toarray

node js mongo find last inserted

I am having a hard time trying to find the last inserted element into mongo. I am using an example code I found and trying to make the query and display the item but I am getting an error. I understand I am suppose to do something like this.
db.collectionName.findOne({}, {sort:{$natural:-1}})
But this is what I have so far and it's not working.
var MongoClient = require('mongodb').MongoClient;
MongoClient.connect("mongodb://localhost:27017/exampleDb", function(err, db) {
if(err) { return console.dir(err); }
var collection = db.collection('test');
var doc1 = {'hello':'doc1'};
var doc2 = {'hello':'doc2'};
var lotsOfDocs = [{'hello':'doc3'}, {'hello':'doc4'}];
collection.insert(doc1);
collection.insert(doc2, {w:1}, function(err, result) {});
collection.insert(lotsOfDocs, {w:1}, function(err, result) {});
collection.find({}).toArray(function(err, docs) {
console.log(docs[0]);
});
db.close();
});
This is the error.
nodejs/node_modules/mongodb/lib/mongodb/connection/base.js:246
throw message;
^
TypeError: Cannot read property '0' of null
I checked to make sure the database is not empty so I am not sure why it's returning null.
I've found a possible solution(here) to your problem. It might be due to the fact that the database connection closes before the operations that you have issued finish.
You can fix it by including the db.close() call inside the find query.
collection.find({}).toArray(function(err, docs) {
console.log(docs[0]);
db.close();
});

PUT request in Restify API, NodeJS, MongoDB

I am trying to write a PUT request for my API. I'm using restify to build the API.
I keep getting the errors, could you please help?
//PUT (Update) Items
app.put('/items/:item_id', function(req, res){
var query = Item.where({_id: req.params.item_id});
query.findById(req.params.id, function (err, items) {
item.name = req.body.name;
item.description = req.body.description;
item.url = req.body.url;
req.item.save(function (err) {
if (!err) {
console.log("updated");
} else {
console.log(err);
}
res.send(204, item);
});
});
I tried testing it using POSTMAN client and I get this error
{
"code": "InternalError",
"message": "Object #<Query> has no method 'findById'"
}
Thanks.
The findById method internally maps to find with the parameter {_id: }
You can use either:
Item.find({_id: req.params.item_id}, function (err, items) {
});
or
Item.findById(req.params.item_id, function (err, items) {
});
Both are the same thing. The reason is because when you write
var query = Item.where({_id: req.params.item_id});
A query object is returned, on which the findById method cannot be called. It can only be called on the Item model.
If you are trying to combine queries, I would suggest combining them at the filter level or use aggregation.

Resources