I'm trying to get the result of query but i get the same info in all vars: db, collection and res:
var mongodb = require("mongodb");
var mongoserver = new mongodb.Server("localhost", 27017);
var instance = new mongodb.Db("test", mongoserver);
instance.open(function(err, db)
{
console.log('db:');
console.log(db);
db.collection('kurtsoa', function(err, collection)
{
console.log('collection:');
console.log(collection);
collection.find({}, function(err, res)
{
console.log('res:');
console.log(res);
});
});
});
how i can get the result of "find"?
.find() will return a Cursor object for you to work with. If all you are interested in is getting all the results in an array you can do:
collection.find().toArray(function(err, docs) {
console.log(docs);
});
But you can also iterate the cursor too:
collection.find().each(function(err, doc) {
//called once for each doc returned
});
You can use this:
collection.find().toArray(function(err, docs){
console.log(docs);
)};
Related
In the code I am trying to find all documents with code UE19CS204.But in the console.log
a big message is printed not the JSON data.The findOne() is working but not find().
I don’t know what change to do to find all documents with code UE19CS204.
var MongoClient = require(‘mongodb’).MongoClient;
var url = “mongodb://localhost:27017/”;
MongoClient.connect(url, { useUnifiedTopology: true } ,function(err, db) {
if (err) throw err;
var dbo = db.db(“pes”);
dbo.collection(“course”).find({“code”:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
});
dbo.collection(“course”).findOne({code:“UE19CS204”}, function(err, result) {
if (err) throw err;
console.log(result);
db.close();
});
});
The method find() creates a cursor for a query that can be used to iterate over results from MongoDB, see here.
Use toArray(), you can finde the documentation here.
dbo.collection(“course”).find({“code”:“UE19CS204”}).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
Full example:
const MongoClient = require('mongodb').MongoClient;
// Connection URL
const url = 'mongodb://localhost:27017';
// Database Name
const dbName = 'pes';
// Collection Name
const collectionName = 'course';
// Filter
const filter = { 'code': 'UE19CS204' }
// Use connect method to connect to the server
MongoClient.connect(url, { useUnifiedTopology: true }, function(err, client) {
if (err) {
throw err;
}
client.db(dbName).collection(collectionName).find(filter).toArray(function(err, docs) {
if (err) {
throw err;
}
console.log(docs);
})
client.close();
});
I need to update the data from client side in mongodb but I can see clicked updated Id value in node js but it does not update in mongodb wat to do.. help me to update the values in mongo db using id values
router.post('/datapassfup', (req, res) => {
console.log("updated values are",req.body)
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var dbo = db.db("mohan");
var myquery = { id: req.body.id };
var newvalues = { $set: {name: req.body.name, username:
req.body.username } };
dbo.collection("customers").updateMany(myquery,newvalues,
function(err, res) {
if (err) throw err;
console.log("1 document updated");
db.close();
});
});
});
if you use the mongodb id for you query then you need to create a new objectid for _id search
const {ObjectId} = require("mongodb");
const query = {_id:new ObjectId(req.body.id)}
I am new with express js and node js. I am wonder if its possible to do this or not.
1st thing I'm trying to get the count on 1 query.
2nd I query collection login. loop it and format and get the name values using ids.
I get undefined on count1 and I see it ommitted on the json response.
how do I pass the query returns outside of the query?
router.post('/logmein', function(req, res, next) {
var email = req.param('email');
var password = req.param('password');
var count1;
MongoClient.connect(MongoUrl, function(err, db) {
if (err) return;
db.collection('users').count({email: email,password: md5(password)}, function(err, count) {
count1 = count;
});
db.collection('login').find({email: email,password: md5(password)}).toArray(function(err, results){
console.log(results); // output all records
});
//use results
/*
foreach each results format with other info
var new_array;
*/
res.json({"success": true,"count":count1,new_array: new_array});
});
});
Async issues, you have to look more at it. Use the async module and then you will be able to fire the queries in parallel. Finally, you will have the results in the final callback. This snippet will fix your issue:
var async = require('async');
router.post('/logmein', function (req, res, next) {
var email = req.param('email');
var password = req.param('password');
var retResults;
var count1;
MongoClient.connect(MongoUrl, function (err, db) {
if (err) return;
async.parallel([
function(callback){
db.collection('users').count({ email: email, password: md5(password) }, function (err, count) {
return callback(err, count);
});
},
function(callback){
db.collection('login').find({ email: email, password: md5(password) }).toArray(function (err, results) {
return callback(err, results);
});
}
], function(err, results) {
if (err) {
// #todo: handle the error
}
count1 = results[0];
retResults = results[1];
//use results
/*
foreach each results format with other info
var new_array;
*/
res.json({ "success": true, "count": count1, new_array: new_array });
};
});
});
You need something like async.parallel to control the async flow of your nodejs application
async.parallel([
function(callback){ ... },
function(callback){ ... }
], function(err, results) {
// optional callback
};
I need to store responses to questions in Mongo. I am using Mongoose. My query looks like this right now:
router.post('/answers', expressJwt({secret: config.secret}), function (req, res, next) {
var user = req.user
var question = req.body.question
var answer = req.body.answers
var id = question._id
db.User.update({email: user.email}, {$set: {answers[question._id]: answer}}, function (err, doc) {
if (err) {
console.error('problem updating answers object', err)
return res.json(err)
}
console.log(doc)
return res.json('successfully updated answers')
})
})
I get an error 'unexpected token [' How can I add properties to my answers object?
I had to make a db call to get the answers object, then modify it, then update it back to the db. Here is the code I used. Note: use lean and exec with mongoose to get raw object otherwise you will run into problems modifying mongoose objects.
router.post('/answers', expressJwt({secret: config.secret}), function (req, res, next) {
var user = req.user
var question = req.body.question
var answer = req.body.answers
var id = question._id
db.User.findOne({email: user.email}).lean().exec(function (err, user) {
user.answers[question._id] = answer
db.User.update({email: user.email}, {$set: {answers: user.answers}}, function (err, doc) {
if (err) {
console.error('problem updating answers object', err)
return res.json(err)
}
console.log(doc)
return res.json('successfully updated answers')
})
})
})
First,you have to set id in your answer object before database call,then replace your field with your new field
router.post('/answers', expressJwt({secret: config.secret}), function (req, res, next) {
var user = req.user
var question = req.body.question
var answer = req.body.answers
answer.question._id = question._id;
db.User.update({email: user.email}, {$set: {answers: answer}}, function (err, doc) {
if (err) {
console.error('problem updating answers object', err)
return res.json(err)
}
console.log(doc)
return res.json('successfully updated answers')
})
})
Store it in a variable instead of using the literal object syntax:
var $set = {};
$set[answers[question._id]] = answer;
db.User.update({email: user.email}, {$set: $set}, function (err, doc) {
// ...
Also, if you have ES6 features available to you (e.g. a recent version of io.js) you can use the special bracket notation in object literals to achieve the same thing:
db.User.update({email: user.email}, {$set: {[answers[question._id]]: answer}}, function (err, doc) {
// ...
I have this function to retrieve a specific user from a mongo db:
exports.findById = function(req, res){
var id = req.params.id;
db.collection('Users', function(err, collection){
collection.findOne({'_id':new BSON.ObjectID(id)}, function(err, item){
findPhotoByUserId(item._id, function(photo){
console.log('photo: ' + photo);
});
});
});
};
And this other to get the photo of the user, passing to it the Id of the user:
var findPhotoByUserId= function(userId, cb){
db.collection('Photos', function(err, collection){
collection.findOne({'userId': userId}, function(err, item){
if(!err)
cb(item);
});
});
};
Problem: the photo item is being null when i call the function "findById". However, if i put the explicit User Id here "collection.findOne({'userId': '522bae4a3ee1be8005000001'}....", the function returns the expected photo item.
Can someone help me about this issue?
Thanks!
I had the same problem. I got my code to work by using ObjectID in the 'mongodb' library:
var ObjectID = require("mongodb").ObjectID;
//more code here
query._id = { $gt: ObjectID(myId) }
Well, i solved my problem!
At this function:
var findPhotoByUserId= function(userId, cb){
db.collection('Photos', function(err, collection){
collection.findOne({'userId': userId.toString()}, function(err, item){
if(!err)
cb(item);
});
});
};
the 'userId' must be converted do a string.
Thanks!