My schema looks like the following:
const userSchema = new Schema({
...
followings: [
{
user:{
type: Schema.ObjectId,
ref: 'User'
},
}
],
followers: [
{
user:{
type: Schema.ObjectId,
ref: 'User'
},
}
],
}, {timestamps: true})
And I need to implement "unfollow" feature.
I am currently trying this:
try {
// check if your id doesn't match the id of the user you want to unfollow
if (user._id === current_id) {
return res.status(400).json({ error: 'You cannot unfollow yourself' })
}
// remove the id of the user you want to unfollow from following array
const query = {
_id: current_id
}
const update = {
$pull: { "followings": {"_id": user._id }}
}
const updated = User.update(query, update)
// remove your id from the followers array of the user you want to unfollow
const secondQuery = {
_id: user._id
}
const secondUpdate = {
$pull: { "followers": {"_id": current_id} }
}
const secondUpdated = User.update(secondQuery, secondUpdate)
if (!updated || !secondUpdated) {
return res.status(404).json({ error: 'Unable to unfollow that user' })
}
res.status(200).json({
update,
secondUpdate
})
}
catch (err) {
res.status(400).send({ error: err.message })
}
This gives status 200 and sends update & secondUpdate to the client,
but the actual object doesn't get deleted from the database.
What is wrong with my code?
If you are using mongodb native drive
You should import mongodb ObjectID. Before performing operations.
const ObjectId = require('mongodb').ObjectID;
$pull: { "followers": {"_id": current_id} }
change to:
$pull: { "followers": {"_id": new ObjectId(current_id) }
Thank you for your answers.
In my case, the following worked for me.
try {
// check if your id doesn't match the id of the user you want to unfollow
if (user._id === current_id) {
return res.status(400).json({ error: 'You cannot unfollow yourself' })
}
// remove the id of the user you want to unfollow from following array
const query = {
_id: current_id
}
const update = {
$pull: { followings: {_id: user._id }}
}
const updated = User.updateOne(query, update, {
safe: true
}, function(err, obj) {
console.log(err);
})
// remove your id from the followers array of the user you want to unfollow
const secondQuery = {
_id: user._id
}
const secondUpdate = {
$pull: { followers: {_id: current_id} }
}
console.log(secondQuery)
console.log(secondUpdate)
User.updateOne(secondQuery, secondUpdate, {
safe: true
}, function(err, obj) {
res.status(200).json({
obj
});
})
}
catch (err) {
res.status(400).json({ error: err.message })
}
Related
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!!'
})
}
}
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 },
}
);
I have been trying to remove elements from the array, seem like it's not working, here is the model
1. Question Model
{
reviews: [{ type: ObjectID, ref: 'Review' }]
}
2. Review Model
{
description: {
type: String
},
userId: {
type: ObjectId,
ref: 'User'
}
}
And here is my service for the Quuestion.js
export const deleteReview = async ({ reviewId, id }, user) => {
try {
const result = await Question.updateOne(
{ _id: id },
{
$pull: { reviews: { _id: reviewId, userId: user._id } }
}
).exec();
if (result.nModified === 0) {
throw new APIError({ message: msg('Unauthorized'), status: 401 });
}
return result;
} catch (error) {
throw error;
}
};
Routes file
router.delete('/questions/:id/reviews/:reviewId', auth, async (req, res) => {
try {
const {
params,
user
} = req;
const data = await deleteReview( params,
user);
return res.status(200).json({ data });
} catch (err) {
error(res, err);
}
});
I was trying to remove the elements but it's not removing at all, I have no idea where I did a mistake.
Here is the solution I got, the $pull is not working so applied the $pullAll
export const deleteReview = async ({ reviewId, id }, user) => {
try {
const result = await Question.updateOne(
{ _id: id },
{
$pullAll: { reviews: [{ _id: reviewId, userId: user._id }] }
}
).exec();
if (result.nModified === 0) {
throw new APIError({ message: msg('Unauthorized'), status: 401 });
}
return result;
} catch (error) {
throw error;
}
};
I try to store friends in my friends collection. This collection contains a field userId which is an array of user ids. When I store the same id again I want mongoose to throw an error.
My friend schema looks like this:
const friendSchema = mongoose.Schema({
_id: mongoose.Schema.Types.ObjectId,
userId: [{
type: mongoose.Schema.Types.ObjectID,
unique: true,
required: true,
ref: 'User',
}],
});
I am calling it like this:
Friends.findByIdAndUpdate({_id: req.userData.userId}, {$addToSet: { userId: req.body.id } }, {safe:false, upsert: true}, function (error, friend) {
if(error){
return res.status(500).json({
message: 'You already added this user as friend! ' +error,
});
}else if (!friend) {
return res.status(401).json({
message: 'Authentication failed',
});
} else {
Friends.
find({_id: req.userData.userId})
.populate('userId')
.exec(function(error, posts) {
if(!error) {
let returnValue = [];
posts.map((x)=>{
returnValue = x.userId;
})
return res.status(200).json(returnValue);
}else {
return res.status(400).json({message: error.message});
}
})
}
const userSchema = new mongoose.Schema({
name: String,
products: []
});
eg. User:
{ name: 'Steve', products: ['111a', '222b']}
I want to remove the product of given name from the user of given ID.
User.findByIdAndUpdate(userId, { $pull: { products: req.body.prodId } }, (err, user) => {
if (err) { res.send('error_3853852'); return; }
res.send('updated'); return;
})
As a result it is not removed and no error occured
I am working on node.js express framework and mongoose and I am totally new to it.
This is my schema.
const mongoose = require('mongoose');
const ActivitySchema = mongoose.Schema({
_id: mongoose.Schema.ObjectId,
Activity:String,
Photos:[{
Photo:String,
}]
});
module.exports = mongoose.model('Activity', ActivitySchema);
This is my code.I am getting success on deleting but data is not deleted from database.
router.delete('/removeactivity/:_id/:_pid', function (req, res) {
Activities.findByIdAndUpdate(
{ _id: req.params._id },
{ $pull: { Photos: { _id:req.params._pid } } },
function(err,user) {
if(err) {
res.status(500).json(err);
}
res.status(200).json(user)
}
);
})
You are using mongoose.Schema.ObjectId, so your _id field is an ObjectId. In the delete logic you pick req.params._id, which is, I guess, a string and not ObjectId, so it won't work.
To create an ObjectId from a string, use mongoose.Types.ObjectId like this:
Activities.findByIdAndUpdate(
{ _id: mongoose.Types.ObjectId(req.params._id) },
...
)
To get the new version of the document, after the update is applied, put {new: true} in the query. By default it is false.
Activities.findByIdAndUpdate(
{ _id: req.params._id },
{ $pull: { Photos: { _id:req.params._pid } } },
{new : true},
function(err,user) {
if(err) {
res.status(500).json(err);
}
res.status(200).json(user)
}
);
})