Home > Mobile >  I am having this issue in my project using mongodb with node js
I am having this issue in my project using mongodb with node js

Time:09-20

In my project when an company owner creates a new employee account, I need to add all the existing employee to be friends with the new employee that is created. Currently my code works in such a way that the owner can be friends the employee that it has created but, two employee cannot be friends with each other. How can I do this ?

const addCompanyEmployee = async(req, res) => {
try {
const { name, location, email, password,username, companyId} = req.body;
console.log(req.params.Id)
if(!name || !username || !location || !email || !password || !companyId){
  return res.status(400).json({
    status: 'failed',
    message: 'please provide all the values'
  })
}
const userAlreadyExists = await Users.findOne({ email });
if (userAlreadyExists) {
  return res.status(400).json({
    status: 'failed',
    message: 'User Already exists'
  })  
}
if(email && companyId){
  const emailVerified = await CompanyRegistered.findById(companyId)
  if(!emailVerified && !emailVerified.IsActive){
    return res.status(404).json({
      status: 'Failed',
      message: 'The company is not registerd or verified yet'
    })
  }
const user = await Users.create({
  name,
  username,
  location,
  email,
  password,
  companyId
});
await Users.findOneAndUpdate(
  { _id: req.params.Id },
  {
    $push: { friends: user._id },
  },
  { new: true }
);
await Users.findOneAndUpdate(
  { _id: user._id },
  {
    $push: { friends: req.params.Id },
  },
  { new: true }
)

res.status(200).json({
  user: {
    email: user.email,
    location: user.location,
    name: user.name,
    username:user.username,
    companyId: user.companyId,
    friends: user.friends
  },
  location: user.location,
});
}
 } catch (error) {res.status(500).json({
  status: 'failed',
  message: 'Something went wrong in our application. Please try again later!!'
 })
 }
}

CodePudding user response:

You should be able to use db.collection.updateMany() to update all users with the new friend:

await Users.updateMany(
  {}, // update all documents
  {
    $push: { friends: req.params.Id },
  }
);

To make sure that the id is only added if its not part of the friends array yet, you can use $addToSet:

await Users.updateMany(
  {}, // update all documents
  {
    $addToSet: { friends: req.params.Id },
  }
);
  • Related