find all documents using mongoose - node.js

Im trying to find all documents in a DB using mongoose but I cant do it
I want to do it this way but I don't know what's wrong with it
app.get('/users', function (req, res){
User.find({}, 'name', function(err, user){
if(err){
console.log(err);
}else{
res.render('user-list', {
name : user.name
});
console.log('retrieved list of names' + user.name);
}
})
})
When I use User.findOne({}, 'name', function(err, user){.. I get back the first doc which is what I would expect. Please explain why the code above is not allowing me to get all documents. I feel like I'm using it the right way as show in the mongoose doc
Edit
thanks for help guys
i did like this:
app.get('/users', function (req, res){
User.find({}, 'name', function(err, users){
if(err){
console.log(err);
}else{
res.render('user-list', {
name : users.map(function(doc){
return doc.name + "<br>"
})
});
console.log('retrieved list of names' + users.name);
}
})
})
can some one please help me with getting each name on a new line the "<br>" shows up on the page but it doesn't make a new line "<br>,Joe<br>,mike<br>"
Jade:
extend layout
block content
p list of users #{name}

app.get('/users', function (req, res){
User.find({}, 'name', function(err, users){
if(err){
console.log(err);
} else{
res.render('user-list', users);
console.log('retrieved list of names', users.length, users[0].name);
}
})
});
As said in the comments, find can find many objects, so it returns an array as contrasted with findOne that returns a single object. Adjust for that as above and you should be back on track.

app.get(`/users`, async (req,res)=>{
try{
const users = await User.find({}).exec()
users && res.render('user-list',users)
}catch(error){
res.status(500).json({error})
}
})
//OR
app.get(`/users`, async (req,res)=>{
try{
const users = await User.find({}).exec()
const list = new Array()
for(let row of users){
list.push(`${users.name}<br>`)
}
list ? res.status(200).send(list) : res.status(200).json({message: 'Users list is empty'})
}catch(error){
res.status(500).json({error})
}
})
In second example you send to client a text line!!!

Related

Send multiple collections to one ejs file using mongodb and nodejs

app.get('/index', function(req, res){
Activities.find({}, function(err, activity){
if(err){
console.log(err);
}else{
res.render('index', {activities:activity});
}
});
Upcoming.find({}, function(err, upcomingActivity){
if(err){
console.log(err);
}else{
res.render('index', {upcoming:upcomingActivity});
}
});
});
I just want to get data of multiple collections and then pass it to index.ejs file so that i can use these data there.
I know using res.render() multiple times won't work but i have tried many things like saving founded data to variable , creating an object of these etc. But nothing
worked.
In your get response you should render only once the index page passing the parameters all together.
app.get('/index', function(req, res){
Activities.find({}, function(err, activity){
if(err){
console.log(err);
}else{
Upcoming.find({}, function(err, upcomingActivity){
if(err){
console.log(err);
}else{
res.render('index', {activity:activity, upcoming:upcomingActivity,});
}
});
}
});
});
It will work this way, since you have only a few collections but other way to do so is passing it as a global object and then rendering it.
Use then to render asynchronously
app.get('/index', (req,res) => {
Activities.find().then(activity => {
Upcoming.find().then(upcomingActivity => {
res.render('index', {Activities: activity, Upcoming: upcomingActivity})
}).catch(err => console.log(err))
}).catch(err => console.log(err))
})

Mongoose find not returning the full collection

I am trying to read data from an html form through a POST, store it in a mongoDB and query it using model.find() and print it in console. But when i run this for the first time the find() is returning an empty object and on giving the next input the previous data excluding the current input is retrieved by th find(). How can i print the full collection including the freshly entered data
app.post("/", function(req, res){
postTitle = req.body.postTitle;
postDesc = req.body.postDesc;
const post = new Post({
title:postTitle,
desc:postDesc
});
post.save();
Post.find({}, function(err, data){
if(err){
console.log(err);
}else{
console.log(data);
}
});
//console.log(postTitle, postDesc);
});
The command post.save(); will just begin working and your code will continue meanwhile. When your Post.find({} ... starts working, your post.save(); haven't finished working, and thus you're not getting the results.
Change the function so you wait for the save to give you a callback with an ok and then you can query the database.
app.post("/", function(req, res) {
const postTitle = req.body.postTitle;
const postDesc = req.body.postDesc;
const post = new Post({
title: postTitle,
desc: postDesc
});
post.save(function(err) {
if (err) {
// Something went wrong with the save, log and return the error message
console.error(err);
return res.send(err);
}
console.log(`Post "${postTitle}" saved to database.`);
// Since we know that the post has been saved, continue querying the database.
Post.find({}, function(err, data) {
if (err) {
// Something went wrong with the query, log and return the error message
console.error(err);
return res.send(err);
}
console.log(data);
res.send(data);
});
});
});
This code is not tested.
You can also try async/await out, see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function and also mongoose documentation for promises & async/await https://mongoosejs.com/docs/promises.html.
I myself would write the function like this using async/await and es6.
app.post('/', async(req, res) => {
const post = new Post({
title: req.body.postTitle,
desc: req.body.postDesc
});
try {
await post.save();
const posts = await Post.find();
console.log(posts);
} catch (err) {
console.error(err);
}
res.end();
});
You can try with exec
Post.find({}).exec(function (err, d) {
if(err){
console.log(err);
}else{
console.log(d);
}
});
Or try to use async await to make sure your query is running step by step
const user_info = await Post.find({});
This code is not tested
here post.save() is an async function that means it does not complete immediately. You need to use async - await in order to wait for the save() function to finish and then you query the database.

Mongoose and Express, How can I get unique records from db?

In my database, I have 2-3 records with title (Article one).
How can I get only 1 result?
Following is my code that doesn't work,
app.get('/', (req, res) => {
Article.find.distinct(title, (err, title) => {
if(err){
console.log(err);
} else {
console.log(articles);
res.render('index', {
title: 'Articles',
articles: title
});
}
});
});
But if I use,
Article.find({}, (err, title)
it works, but I do not need objects because they are all unique
I tried this link
How do I query for distinct values in Mongoose?
But it does not work for me.
For example, I have records:
One, Two, One
But need output: One, Two
You need to use distinct operator with the desired property (here, title) passed as parameter like this,
app.get('/', (req, res) => {
Article.distinct('title', function(error, titles) { //see the use of distinct
if (err) {
console.log(err);
} else {
console.log(articles);
res.render('index', {
title: 'Articles',
articles: titles
});
}
});
});
The following query will return an array of title, all distinct.
Hope this resolves the issue.

GET request for specific id returning null

I'm attempting to build a simple CRUD application using express and mongodb. My GET request for all database entries is working and my POST request is working but I can't seem to figure out the problem with my GET request for individual entries.
Server.js GET request:
app.get('/api/:id', function (req, res) {
var id = req.params.id;
db.collection('api').findOne({_id: id}, (err, result) => {
if (err){
res.sendStatus(404);
return console.log(err);
}
res.redirect('/');
return console.log(result);
});
});
When I type 'url/api/593555074696601afa192d7f' which is an ID I know exists the console.log is returning null, I'm not sure if I'm doing something wrong?
You should pass ObjectID instance in the query.
let ObjectID = require("mongodb").ObjectID;
app.get('/api/:id', function (req, res) {
var id = req.params.id;
db.collection('api').findOne({_id: ObjectID(id)}, (err, result) => {
if (err){
res.sendStatus(404);
return console.log(err);
}
res.redirect('/');
return console.log(result);
});
});
Give Mongoose a try. It might be of help if your models get complex.

Mongoosedb: query by username

Problem Question: I am using MongooseDB with Nodejs and I have user schema
var UserSchema = new mongoose.Schema({
userEmail: String
});
how would I query using the userEmail?
I tried following but no result. On my postman i get cast to ObjectId failed error
router.get('/:userEmail', function(req, res, next) {
User.find(req.params.userEmail, function (err, userDetails) {
if(err){
return next(err);
}res.json(userDetails);
})
});
You need to create a query object or document that has the userEmail property and a value from the req.params object. In your case, this would be:
router.get('/:userEmail', function(req, res, next) {
User.find({ "userEmail": req.params.userEmail }, function(err, userDetails) {
if(err){
return next(err);
}
res.json(userDetails);
});
});
Please try this syntax
router.get('/:userEmail', function(req, res, next) {
User.find({"userEmail":req.params.userEmail}, function (err, userDetails) {
if(err){
return next(err);
}res.json(userDetails);
})
});
You have to put condition on which field you want to query data.
I am unable to reproduce your error "ObjectId failed error". However, I am adding another answer to give you more options.
The following things are slightly different from other answers:-
1) "lean()" is used to ensure that you will be returned a plain JavaScript object
2) Excluded the "_id" from JSON response though I am not sure whether you need the "Id" in the response. This is just to check whether "id" in response is causing the problem.
router.get('/:userEmail', function(req, res, next) {
User.find({"userEmail": req.params.userEmail}, {"_id":false}).lean().exec(function(err, users) {
if (err) {
return next(err);
}
console.log(users);
res.json(users);
});
});

Resources