this is my question.js and user.js schema model with mongoose as below, could anyone help how to populate all the username lists in array object of likes:[] with Node js because I was facing this problem almost 2 weeks now, I could not populate the username from a user inside likes. Please, I appreciate your suggestion.
question schema model
user schema model
To populate user details, Please use
Post.findOne( { _id: id } )
.populate( "user" )
.populate( "likes.user" );
To get liked post, please use
Post.find({ "likes": { "$gt": 0 } }, function(err, data) {
})
or using where, here may get error if likes fields is missing or empty, so please check if it is exists
Post.find( {$where:'this.likes.length>0'} )
so please use where and exists
Post.find( {likes: {$exists:true}, $where:'this.likes.length>0'} )
I tried your code and got it working using your model. If you are using user only you can directly call .populate("user") but if its nested you need to do .populate("likes.user")
Post.findOne( { _id: id } ).populate( "user" ).populate( "likes.user" );
Yes, thank you to Ratnadeep Bhattacharyya, now I able to populate username in likes array object and also able to return the only a specific array of likes. Below is the working code:
Happy Coding, Jonh
//#route api/post/get/likes
router.get('/get/likes/:postId', auth, async (req, res) => {
try {
//check if post exist
const likes = await Post.findOne({ _id: req.params.postId })
.populate('user', ['name'])
.populate('likes.user', ['name']);
return res.status(200).json(likes.likes);
} catch (error) {
console.log(error.message);
res.status(500).json({ msg: 'Server error' });
}
});
Related
I'm a beginner in MongoDB and have been following a tutorial from one year ago. I send a PUT request with the following json:
{
"username": "NoMore"
}
Then I use findByIdAndUpdate() with the _id being pulled from the url's :id params. The function is async, but await is used on the update function. Despite the code seeming to have worked one year ago, I can not find any updated information regarding this online.
My entire function is as follows:
router.put('/:id', verifyTokenAndAuthorization, async (req, res) => {
if (req.body.password) {
req.body.password = CryptoJS.AES.encrypt(
req.body.password,
process.env.PASS_SEC
).toString();
}
try {
const updatedUser = await User.findByIdAndUpdate(
req.params.id,
{
$set: req.body,
},
{ new: true },
);
res.status(200).json(updatedUser);
} catch(err) {
res.status(500).json(err);
}
})
I have tried setting the _id manually as a string, but the code still went to an error 500. I also preset the req.body which did not change the result.
I am expecting for the user's username to become the username sent in the PUT request.
I didn't import the model (User) so there was no connection to MongoDB.
I put the following code at the top:
const User = require('../models/User');
Now it works fine.
I get that this can be a duplicated question. I looked up at least 10 related questions and answers, but I am still not able to find the document.
I am trying to get the document using .findOne(). I have the _id that created by MongoDB. But, I get null for every search I try.
await mongoose.connection.db
.collection('testing')
.findOne({ _id: req.body.test_id }, (err, result) => {
if (err) {
res.status(400);
} else {
console.log(`whaaaaaahsidufh ${result}`);
}
});
I tried _id: mongoose.Type.ObjectId(req.body.test_id) and other possible way to search. How can I retrieve the result by using _id on mongoose?
you can use findById();
try {
const test = await mongoose.connection.db.collection('testing').findById(req.body.test_id);
if (test ) {
console.log(`whaaaaaahsidufh ${test}`);
} else {
console.log(`test not found`);
}
}catch(err){
res.status(400);
}
MongoDB user entry
Controllers code:
module.exports.deleteIncome = (params) => {
return User.findById(params.userId) // I went to the user here
.then((user, err) => {
if(err) return false
user.incomeRecords.remove( "_id": "{params.incomeRecordId}" ) // my delete income record syntax
return user.save()
.then((updateUser, err) => {
return(err) ? false : true
})
})
}
Here's my code, it's not working
Please see the pic i provided
I want to delete the specific income record inside the user's array incomeRecords
Please help thanks =)
You can use the mongodb pull operator. It would look something like this:-
findOneAndUpdate({userid:params.userid},{
$pull:{
incomeRecords:{
_id:<the mongodb id here>
}
}
})
Check out the mongodb docs
Guys I want to make a unfollow request with $pull qıery but it doesnt work. How to solve this?
Also this method works fine with $push query when I want to follow request user but it doesnt work with $pull.
My app.js:
app.post('/unfollow/:id', function(req, res){
User.find(req.user
).exec(function(err, user){
if(err){
console.log(err);
}
User.find({"username":req.params.id}, function(err, friend){
if(err){
console.log(err);
}
User.update(user,{$pull: { follow: friend}}, function(err){
if(err){
console.log(err);
}else{
res.send("Success")
}
});
});
});
});
This is my how user's follow look like:
{ follow:
[ 5edfe8f3bfc9d677005d55ca,
5edfe92fbfc9d677005d55cc,
5ee2326cc7351c5bb0b75f1a ],
I will take friend id from this array.
And my user model(Follow part):
follow:[{
type: ObjectId,
}]
If pull doesnt work can you suggest me queries or ways to do unfollow request.
User.find({ username: req.params.id } would return a document but looks like you do store ObjectIds in follow field. I except changing $pull: { follow: friend } to $pull: { follow: friend._id } should solve the problem.
I'd like to update some data in Mongoose by using array value that I've find before.
Company.findById(id_company,function(err, company) {
if(err){
console.log(err);
return res.status(500).send({message: "Error, check the console. (Update Company)"});
}
const Students = company.students;
User.find({'_id':{"$in" : Students}},function(err, users) {
console.log(Students);
// WANTED QUERY : Update company = null from Users where _id = Students[];
});
});
Students returns users._id in array with object inside, and I use that to find users object, and then I want to set null a field inside users object, that field named as "company". How I can do that? Thank you.
From what you posted (I took the liberty to use Promises but you can roughly achieve the same thing with callbacks), you can do something like:
User.find({'_id':{"$in" : Students}})
.then( users =>{
return Promise.all( users.map( user => {
user.company = null;
return user.save()
}) );
})
.then( () => {
console.log("yay");
})
.catch( e => {
console.log("failed");
});
Basically, what I'm doing here is making sure .all() user models returned by the .find() call are saved properly, by checking the Promised value returned for .save()ing each of them.
If one of these fails for some reasons, Promise.all() return a rejection you can catch afterhand.
However, in this case, each item will be mapped to a query to your database which is not good. A better strategy would be to use Model.update(), which will achieve the same, in, intrinsically, less database queries.
User.update({
'_id': {"$in": Students}
}, {
'company': <Whatever you want>
})
.then()
use .update but make sure you pass option {multi: true} something like:
User.update = function (query, {company: null}, {multi: true}, function(err, result ) { ... });