Loop custom array from mongoose returned empty - javascript

here is my problem
I want to loop data from two entities Project and User, my Project entity have a field with User id called creatorId.
I looped it and tried to add my user data _id, displayname and avatarUrl.
For now that work, but when I send it from the backend to the frontend nothing appears, like the array is empty.
const projectList = [];
Project.find({}, function(err, projects) {
projects.map(project => {
User.findById(project.creatorId, function(err, creator){
projectList.push({
_id: project._id,
title: project.title,
description: project.description,
avatarUrl: project.avatarUrl,
creationDate: project.creationDate,
projectCreator: {
_id: creator._id,
displayname: creator.displayname,
avatarUrl: creator.avatarUrl
},
git: project.git
})
})
})
});
res.send(projectList);

Related

Trying to figure out how to get my MongoDB Database to bring up items that belong to a certain user (by ID)

I'm trying to get my Mongo Database to extract out the items (Portfolio pics) that a user has submitted, but when I previewed the items extracted via the Console logs,it displayed all of the portfolio pieces for everyone instead of just that specific user.
Here are the codes that I typed in Javascript to attempt to get it to work so far:
On the back end side:
(For the routes)--------------------------------------
//GET - get all portfolio pieces for a certain user ----------------------
router.get('/:id', Utils.authenticateToken, (req, res) => {
Portfolio.findById({user: req.body._id}).populate('user', '_id firstName lastName displayName')
console.log({user: req.body._id})
.then(userPortfolio => {
if(userPortfolio == null){
return res.status(404).json({
message: "No portfolio pieces found"
})
}
res.json(userPortfolio)
})
.catch(err => {
console.log(err)
res.status(500).json({
message: "Problem getting portfolio pieces"
})
})
})
For the Portfolio Model (Schema) file:
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const Utils = require('./../utils')
// schema
const portfolioSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
description: {
type: String,
required: true
},
user: {
type: Schema.Types.ObjectId,
required: true,
ref: 'User'
},
image: {
type: String,
required: true
},
tag: {
type: String,
required: true
},
link: {
type: String,
}
}, { timestamps: true, collection: 'portfolioPs' })
// model
const portfolioModel = mongoose.model('Portfolio', portfolioSchema)
// export
module.exports = portfolioModel
And for the front end side:
init(){
console.log('ProfileView.init')
document.title = 'Profile'
this.userPortfolio = null
this.render()
Utils.pageIntroAnim()
this.getUserPortfolio()
}
async getUserPortfolio(){
try{
this.userPortfolio = await PortfolioAPI.getUserPortfolio(Auth.currentUser._id)
console.log(this.userPortfolio)
this.render()
}catch(err){
Toast.show(err, 'error')
}
}
Do let me know if you need any further code to help me resolve this issue mates! Thanks in advance!
use Portfolio.find({user: req.body._id}) to get list of of all items that a user has submitted. It will return an array result
P.S:
Portfolio.findById(someId) is used to fetch only 1 specific document where result is an object by matching its _id field

Friend Request System - Express, MongoDB, EJS

I want to create a social network thus allowing users to send and interact with frind requests. As of now I have created the register, log-in and "search for other users function".
When I find and select another user, I display their user-info and have created a "Add friend" button.
Can anyone help me in a direction of the creation of the "Add friend" option? I have looked around for some time now, and not been able to find the correct solution. Below I have attached my UserSchema and route for finding users:
//User Schema
const UserSchema = new mongoose.Schema({
firstName: {
type: String,
required: true
},
lastName: {
type: String,
required: true
},
password: {
type: String,
required: true
},
},{ collection: 'Users' });
//Get single user based on ID
router.get('/user/get:id', ensureAuthenticated, function (req, res) {
MongoClient.connect(DBUri,{useUnifiedTopology: true }, function (err, db) {
let dbo = db.db(DBName);
const query = {_id: objectId(req.params.id)}
dbo.collection("Users").find(query).toArray(function(err, resultTasks) {
if (err) throw err;
res.render('../View/findFriend', {
resultTasks: resultTasks
});
db.close();
});
});
});
You can add something like this in your user schema:
friends: [{ type : ObjectId, ref: 'User' }],
OR
friends: userSchema
Take the one which suits you.
What that will do is add an array to the user, Then you can store IDs of friends.(Who are other users, hence the ref: 'User')
Then, When you have to fetch users you can do:
User.find(<ID or whatever you have to find Users>).populate('friends')
Also, To push a new friend simply use: user.friends.push(newFriend._id)

mongodb: Deleting a user and all data references associated with it

Currently working on a personal website for myself and ran in to some difficulties with mongodb & mongoose when trying to delete a user.
Right now I have two Schema's show below.
UserSchema:
const userSchema = new mongoose.Schema({
username: {
type:String,
required: true,
unique: true,
},
password: String,
firstName: String,
lastName: String,
eMail: String,
status: {type:Boolean, default: true},
hobbies: [
{
type: mongoose.Schema.Types.ObjectId,
ref: "Hobby"
}
]
HobbySchema:
const hobbySchema = new mongoose.Schema({
title: String,
user: {
id: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
},
username: String
},
desc: String,
iconURL: String
});
My issue right now is that when I delete the user using the following route with nodeJS:
router.delete('/delete/:id', async (req,res) => {
await User.findOneAndDelete(req.params.id, (err, foundUser) => {
if(err){
console.log(err);
}else{
res.redirect("/logout");
}
})
});
I run into the issue that the Hobby collection still contains all hobbies that the user created. I'm looking to have them all deleted when the user wants to delete their account.I understand that Mongodb/Mongoose is a non-relation database and is unlike SQL as I'm coming from SQL. Is there any way to delete all hobbies a user created? (Just creating hobbies as a very basic example).
What is the best alternative? Just going with SQL lite and changing the database entirely?
Thanks

How to update document of mongodb using multiple conditions?

I have a post schema that simply has attributes like _id, text, likes and comments. I want to push user id into likes array it if fulfills two conditions. Firstly the id of the post should match the query param and then the likes array should not already contain the id of the person trying to like the post. Instead error msg should come: Post already liked.
Like key pair from post schema
likes:[{
user:{
type: Schema.Types.ObjectId,
refPath:'onModel'
}
}]
I wrote the following query but it doesn't work. The update part works fine but some issue with the first argument.
Post.update({$and: [{ _id: req.params.postid},{"likes": { $ne : { user:
authorizedData.jwt_payload.patient._id }}}]},
{ $push: { likes: {user: authorizedData.jwt_payload.patient._id }}})
.then(post => res.json(post))
.catch(err => res.json(err))
Any suggestions please?
Ok, it can be simple in this way :
Post.update({
_id: req.params.postid,
'likes.user': {
$ne:
authorizedData.jwt_payload.patient._id
}
},
{ $push: { likes: { user: authorizedData.jwt_payload.patient._id } } })
.then(post => res.json(post))
.catch(err => res.json(err))

mongoose extract nested arrays from multiple objects into one array

const userSchema = new Schema(
{
_id: Schema.Types.ObjectId,
name: String,
posts: [{ type: Schema.Types.ObjectId, ref: "Post" }],
following: [{ type: Schema.Types.ObjectId, ref: "User" }]
}
};
I want to extract all the posts from all the Users in the 'following' array, put them into one single array, sort them and then display the first 20. I was wondering if that is possible within the cursor or if I have to load it into memory.
function createFeed(user) {
User.findOne({ name: user })
.populate({
path: "following",
populate: {
path: "posts"
}
})
//put all the posts into one array
.sort(...) //sort by time created
.limit(...) //only get the newest n posts
.exec((err, result) => {
if (err) console.log("error", err);
console.log("result", //sorted tweets array);
});
};
(I don't want to filter all the posts in my 'Posts' collection to check if they are made by the user since that would be a lot more expensive)
You can use distinct query in mongoDB
db.User.distinct('following',{})
If you are trying to filter your populate with a condition, then you should be doing this:
User.findOne({ name: user })
.populate({
path: 'posts',
match: { user: 'XXX' }
})
Even more better would be to query the posts with the user filter condition and then populate user details.

Categories