Why am I not able to populate the posts field? - javascript

So, as you could see from my previous questions, I've been stuck in populate of mongoose. I have two models, User and Post, and currently, I'm trying to get a single user's posts but not able to do it.
getUserPosts: async (req, res) => {
try {
const user = await User.findById(req.params.id).populate("posts");
if (!user) {
return res.status(400).json({ error: "No user" });
}
return res.status(200).json({ userposts: user.posts });
} catch (err) {
return res.status(500).json({ error: "Server error" });
}
}
The problem is I'm somehow getting an empty array of posts. If I manually push the posts documents post id, then it's working, otherwise it's not.

Related

ReferenceError: err is not defined

I'm started working on my very first API using Mongo, Express and Node. When i tried to make API endponit for one specific user, console throw error ReferenceError: err is not defined. An error appears in the method I already used for auth part, and there it worked fine. The part of code where is the error, on line 5:
exports.userById = (req, res, next, id) => {
User.findById(id).exec(() => {
if(err || !user) {
return res.status(400).json({
err: "User not found"
});
}
req.profile = user //adds profile object in req with user info
next();
});
}
Also, the part of code where I tried to get a single user:
exports.getUser = (req, res) => {
req.profile.hashed_password = undefined;
req.profile.salt = undefined;
return res.json(req.profile);
}
I don't think the problem could be here, but there is also route line from routes file
router.get("/users/:userId", authController.requireSignin, userController.getUser);
Thanks everyone for the help!
I'm pretty sure err comes from exec:
User.findById(id).exec(err => {...});
Edit I guess you want to search by id and return something. Try this.
User.findById(id, (err, user) => {
// if error display errort
if(err) console.error(err);
// if user do not exists
if(!user) {// what is user ? the doc result ?
return res.status(400).json({
"err": "User not found" // i think use ""
});
}
req.profile = user //adds profile object in req with user info
next();
});

Why doesn't 'res.send()' redirect upon completion of MongoDB 'deleteMany' call?

My call to Express's 'res.send(string)' fails to redirect and display the provided text upon completion of a call to MongoDB's 'deleteMany()'. The database is cleared and no error is thrown.
I've tried adjusting my call to 'res' with 'res.json()' and such, but to no avail. I've also adjusted the ordering my other calls within the 'delete' request, with no success. My inclination is that my issue is related to Promises.
.delete(function(req, res){
//if successful response will be 'complete delete successful'
console.log('deleting all documents');
MongoClient.connect(MONGODB_CONNECTION_STRING, { useNewUrlParser: true }, (connectErr, client) => {
if(connectErr) res.json({ "error": "Error connecting to database!", "error": connectErr });
const db = client.db('test-db');
try {
db.collection('testCollection2').deleteMany({}, (err) => {
if(err) throw err;
res.send('complete delete successful');
console.log('complete delete successful');
});
} catch(err) {
console.log('Complete delete failed!');
res.send('Complete delete failed!');
}
});
});
Despite not redirecting or receiving an error message, I still receive the console.log output confirming the successful call to 'deleteMany'. I'm not sure how to test this in more depth, since I'm using Glitch for the project. Thanks in advance for any help!

user.save won't run the callback function

I'm trying to save information to my user schema in my database. I'm doing this using "user.save" but for some reason the code within the parenthesis is not run.
user.save(function(err) {
//THIS CODE DOESNT SEEM TO RUN
if (err) {
console.log(err);
} else {
res.json({ message: 'given a reset-token' })
}
//
});
So I switched to the following code since I needed to get a success message from the server:
user.save((err) => {
console.log('hello');
if (err) {
console.log(err);
console.log('err2');
res.status(404).json({ message: 'Save error' });
}
}).then(() => {
res.status(201).json({ message: 'Activated' });
});
Witch successfully sends me the status code when changes to the user have been pushed to the database. Could anyone explain why the second one works and the first one doesn't? And if there is a better way to write this code?

sequelize find on login retrives always sucess

I am trying to do a simple login using nodejs and sequelize, i already have a user on the database and i try to send the info as req.body and checking if it exist in the where clausure
Like this:
router.post('/', function (req, res, next) {
console.log("hi");
if (JSON.stringify(req.body) == "{}") {
return res.status(400).json({ Error: "Login request body is empty" });
}
if (!req.body.username || !req.body.password) {
return res.status(400).json({ Error: "Missing fields for login" });
}
User.find({ where: { username: req.body.username,password: req.body.password} })
.then(function (user) {
return res.status(200).json({ message: "loged in!" });
}).catch(function (err) {
return res.status(400).json({ Error: "There is no user with those fields" });
});
});
it enters always on the loged in message, even if i send data that doesn't exist on the database, any info why it is happening?
You need to check if user is actually defined:
User.find({ where: { username: req.body.username,password: req.body.password} })
.then(function (user) {
if (! user) {
return res.status(400).json({ Error: "There is no user with those fields" });
} else {
return res.status(200).json({ message: "loged in!" });
}
})
.catch(...)
You're assuming that a query that doesn't yield any results will throw an error, but it won't (because the query ran successfully).
Also, you can make unique index on db to be completely sure that user is unique.
Btw, this index will speed-up login process.
Sequelize index docs ref

How to query all articles from a specific user?

CODE:
server-side
/**
* List of Articles
*/
exports.list = function (req, res) {
Article.find({ 'user.displayName': 'GIGANTOR !' }).sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}
});
};
SITUATION:
What I tried above does not work. I checked the mongoose docs: http://mongoosejs.com/docs/queries.html
but can't seem to get the query to work. Currently, the query just returns nothing.
QUESTION:
How to query all articles by a user with a specific displayName ?
TL;DR You can't query a document by a field that belongs to a populated object.
Since article simply has a ref to User, you'll have just get all articles, and then filter them in memory. Or, since the article.user field is an _id, you can find articles by the user ID (but your question is asking about finding them by user.displayName).
Mongoose populate does not do the populating in the MongoDB server itself; it populates on the application server. This means that multiple round-trips to the database are happening (see article Understanding Mongoose Population.) Therefore, you can't query by a field that exists as part of a populated object.
So, here's your 2 solutions:
Article.find({}).sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
let filteredArticles = articles
.filter(article => article.user.displayName === 'GIGANTOR !');
res.json(filteredArticles);
}
});
Or, if you can query by _id, you can do this:
Article.find({ user: 'somemongoobjectidofuser' }).sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}
});
It gets to be a bit hairy and out of scope of the question, but another solution is the aggregation pipeline, which is only usually recommended for backend analytics. But, it'll provide you more flexibility in your query (especially if you user MongoDB's new $graphLookup).
Or, you can always store a copy of the user as a denormalized object inside the article document itself, but then you run into the much-discussed issue of maintaining denormalized documents in-sync.
Just putting the code I ended up using here for people who could need it:
/**
* List of Articles
*/
exports.list = function (req, res) {
Article.find({ user: req.user._id.toString() }).sort('-created').populate('user', 'displayName').exec(function (err, articles) {
if (err) {
return res.status(422).send({
message: errorHandler.getErrorMessage(err)
});
} else {
res.json(articles);
}
});
};

Categories

Resources