Express.js collection.find() return Object - javascript

I am wanted to display every documents stored in my mongodb. I tried following code which simply get collection.find() and display through res.send()
router.get('/index', function(req,res){
var db = req.db
var collection = db.get('usercollection')
var display = util.inspect(collection.find()));
res.send(display);
});
I expected it to display the actual document stored in mongodb. But instead, it displayed this object format:
{cold:{manager:{driver:[Object], helper:[Object], collection:[Object].....
Is there any other steps needed to display raw mongodb document?

If the library you are using is the official 10gen library, then you can't simply output collection.find() without unwinding it. The easiest way to do that for smaller datasets is
collection.find().toArray(function(err, results) {
if (err) {
// do something error-y
} else {
res.send( results );
}
});
If you post more of your code, and tag your question with the libraries you are using, you'll be able to get more targeted help. If the library you are using returns a promise, this is probably how you'd unwind it:
collection.find().then(function(results){
res.send(results);
}).catch(function(err){
console.error(err);
});

Related

node / express js, get data after query

I know it will be a trivial thing, but for this, I have not found much around, I'm using node/express js to query a database (MySQL), I'm using the following mode for queries:
index.js
exports.view= function(req, res){
var name = req.params.name;
req.getConnection(function(err,connection){
var query = connection.query('SELECT * FROM event WHERE linkname = ?',[name],function(err,rows)
{
if(err){
console.log("Error Selecting : %s ",err );
res.redirect('/');
}else{
console.log("rows: %s",rows);
var body = JSON.parse(JSON.stringify(rows));
console.log("body: %s",body);
res.render('form_payment',{page_title:"Showroom",data:rows});
}
});
});
};
I would like to view the video, or in any case be able to use part of the query data, I read that you can use JSON.stringify(), JSON.parse() or both, but I always print the empty string on the screen, even when I try to print rows:
rows:
body:
The query works perfectly, in fact, I can pass the json of rows to the next activity with res.render (), but in this function (view) I just can not get and then use this data. My idea would be to be able to easily use the contents of rows, for example, something like rows[0].name, rows[0].id or rows.name, rows.code, ...
[SOLVED]
Remember to check if the variables that are passed to the query are correct, once this problem has been solved everything is back to work correctly and access to the rows elements, can occur with rows[0].id, rows[0].name, ...
I hope you can also help you find yourself in this situation.

Azure DocumentDB Stored Procedure in Node.js excute existing

I have been going around in circles with this. I'm trying to execute an existing stored procedure using the node js documentdb library.
var sproc = self.client.queryStoredProcedures(collection._self, "select * from root r WHERE r.id = 'helloWorld'");
self.client.executeStoredProcedure(sproc._self, function (err, res) {
if(err){
console.log(err);
}else{
console.log(res);`
}
});
Not entirely sure queryStoredProcedures (Seems to be no async version of this) is the correct way of retrieving the uri for the store procedure, I haven't managed to get this to work. I'm also trying to avoid too many round trips to the database, but from what I gather I either hard code the store procedure's uri or have to make at least two requests just to execute the stored procedure.
queryStoredProcedures (along with all query and read functions) return a QueryIterator rather than an actual result. The methods you call on the returned QueryIterator are async. So, following the approach of your example (minus error handling), you would do this:
var queryIterator = self.client.queryStoredProcedures(collection._self, "select * from root r WHERE r.id = 'helloWorld'");
queryIterator.toArray(function(err, result) {
var sproc = result[0];
self.client.executeStoredProcedure(sproc._self, function (err, res) {
console.log(res);`
});
});
However, since the introduction of id-based routing, you can short hand the above like this:
var sprocLink = "dbs/myDatabase/colls/myCollection/sprocs/helloWorld";
self.client.executeStoredProcedure(sprocLink, function (err, res) {
console.log(res);`
});

How to create users from array and return their ids in mongoose?

Service get array of users' names, check every name if user with this name exists(if not then create user) and return ids of users with such names. I don't know how to do it because search and save are async.
Following code is for query the collection to get a document based on id .if its found it returns the doc other wise it can inseret the doc for that we used {upsert:true}.this is basic code sample follow mongoose docs http://mongoosejs.com/docs/api.html
Model.findOneAndUpdate({_id:id},{upsert:true}, function(err, doc){
if (err) {
console.log('if error occurs');
} else {
console.log('doc',doc)
}
});
I did it using async library for node js.

NodeJS bulk remove mongodb documents

I have a collection with some bad data. I would like to bulk delete this data based on some query. This is easy in the mongo shell as db.collection.remove() allows you to specify the justOne option. Is there some way to do this in the node.js driver? findAndRemove seems to only delete 1 document and has no option to make it bulk?
db.collection(collection_name, function(err, collection){
collection.findAndRemove({type: 'LUXURY'}, function(err, result){
// result is only a single document
console.log(result._id.toString());
});
});
I know an alternative to this is to find() all documents that satisfy my query and manually create a BulkOp using initializeUnorderedBulkOp and populate it by iterating over the results of my find, but I feel there should be an easier way.
If you are using node-mongo-native driver, I can't see any reason why you don't use the remove directly.
db.collection(collection_name, function(err, collection){
collection.remove({type: 'LUXURY'}, function(err, result){
// your code here.
});
});

Entering data with MongoDb and Node.js

So I'm trying to enter data into a mongodb collection with node. As far as I can tell I have access to the collection.
var collection = db.collection("whatsGoingOnEvents");
if(collection){
console.log("hitting stream");
var stream = collection.find({time: parsedObject.time, endTime: parsedObject.endTime, lon:parsedObject.lon,lat:parsedObject.lat}).stream();
console.log(stream);
stream.on("data",function(data){
console.log("data");
console.log(data);
if(!data){
collection.insert(parsedObject);
console.log("hitting insert");
}
});
stream.on("end",function(){
//dosomething
});
}
parsedObject may or may not have all of those fields - should it matter? I thought if the field was not there then collection.find() is just looking for time to be "undefined", which is still technically a value.
I never hit console.log("data") so I never insert documents. I've been trying to follow this link.
and so am not sure why the insert is not happening. I know that nothing is being added from db.collection.stats();, which tells me the size of the collection is 0.
Oh also, this is what I'm using to connect to Mongo-
var mongo = require('mongodb').MongoClient;
EDIT--
I tried the answer below - that resulted in this error-
lib/mongodb/connection/server.js:481
throw err;
^
Error: Cannot use a writeConcern without a provided callback
at insertAll (/Users/psanker/Google Drive/Coding/Javascript/WhatsGoingOn/node_modules/mongodb/lib/mongodb/collection.js:332:11)
at Collection.insert (/Users/psanker/Google Drive/Coding/Javascript/WhatsGoingOn/node_modules/mongodb/lib/mongodb/collection.js:91:3)
^The above occurred because I hadn't added a callback to the insert.
If your query doesn't match any records (which would seem logical, given that you write that the collection size is 0), the data event handler will never get called (because that will only be called when there's an actual result).
I think you're better off with using findOne and a regular callback:
collection.findOne({ params }, function(err, result) {
if (err)
throw err;
if (result === null) {
collection.insert(parsedObject, { w: 0 });
}
});
Or even an upsert.

Categories

Resources