to find total following and follower - node.js

export const add_followers = async (req: Request, res: Response) => {
reqInfo(req)
let user: any = req.header('user'),
body = req.body,
response: any
console.log("user", user);
try {
response = await userModel.findOne({
_id: ObjectId(body.id), isActive: true, "follow.followers": { $elemMatch: { followedBy: ObjectId(user?._id) } }
}) // body.id -> jene follow karvanu 6 // user.id je follow kare 6
console.log("response", response);
if (response) {
console.log("response cond 1")
let data = await userModel.findOneAndUpdate({ _id: ObjectId(body.id), isActive: true }, {
$pull: { "follow.followers": { followedBy: ObjectId(user._id) } }
}, { new: true })
data = await userModel.findOneAndUpdate({ _id: ObjectId(user._id), isActive: true }, {
$pull: { "follow.following": { followingBy: ObjectId(body.id) } }
}, { new: true })
return res.status(200).json(await apiResponse(200, "unFollow Successfully", data, {}));
}
if (!response) {
console.log("response cond 2")
response = await userModel.findOneAndUpdate({ _id: ObjectId(body.id), isActive: true }, {
$push: {
"follow.followers": {
followedBy: ObjectId(user?._id),
name: user?.userName,
image: user?.userImage
},
$count: "follow.followers"
},
}, { new: true })
await userModel.findOneAndUpdate({ _id: ObjectId(user._id), isActive: true }, {
$addToSet: {
"follow.following": {
followingBy: ObjectId(body.id),
name: body?.userName,
image: body?.userImage
},
$count: "follow.following"
},
}, { new: true })
return res.status(200).json(await apiResponse(200, responseMessage?.addDataSuccess("following"), response, {}));
} else {
return res.status(403).json(await apiResponse(403, responseMessage?.getDataNotFound("user"), null, {}))
}
} catch (error) {
console.log(error)
return res.status(500).json(await apiResponse(500, responseMessage?.internalServerError, {}, error))
}
}
i want to get totalfollower and following in this user can follow complete but did'nt get total number of follower

Related

return new MongoError('Cannot use a session that has ended'); MongoError: Cannot use a session that has ended

Essentially, I am trying to update the winner's points and remove points from the losers, but for some reason, the connection closes before the loop finishes. Any help would be greatly appreciated!
module.exports.PointDistrubtion = async (winnerId, price, buyIn, losersId) => {
return await mongo().then(async (mongoose) => {
try {
await profileSchema
.findOneAndUpdate(
{
userId: winnerId,
},
{
$inc: {
Points: price - buyIn,
},
},
{
upsert: true,
new: true,
}
)
.then(
losersId.forEach(async (userId) => {
await profileSchema.findOneAndUpdate(
{
userId,
},
{
$inc: {
Points: -BuyIn,
},
},
{
upsert: true,
new: true,
}
);
})
);
} finally {
mongoose.connection.close();
}
});
};
Doing this should work:
module.exports.PointDistrubtion = async (winnerId, price, buyIn, losersId) => {
return await mongo().then(async (mongoose) => {
try {
await profileSchema.findOneAndUpdate(
{
userId: winnerId,
},
{
$inc: {
Points: price - buyIn,
},
},
{
upsert: true,
new: true,
},
);
await Promise.all(
losersId.map(async (userId) => {
await profileSchema.findOneAndUpdate(
{
userId,
},
{
$inc: {
Points: -BuyIn,
},
},
{
upsert: true,
new: true,
},
);
}),
);
} finally {
mongoose.connection.close();
}
});
};

how to find in an Array of Objects by id?

I want to use mongoose to find in an array of objects by id.
I have this list:
{
"data":[
{
"_id":"60ce0ea7eb945a22288fd0ba",
"parent":"50ce0e44eb945a22288fd0b1",
"label":"label 1-2",
"ancestors":[
{
"_id":"50ce0e44eb945a22288fd0b1",
"label":"label 1-1"
},
{
"_id":"40ce077e90c6262bdc21aa44",
"label":"label 1"
}
]
},
{
"_id":"50ce0e44eb945a22288fd0b1",
"parent":"60ce077e90c6262bdc21aa55",
"label":"label 1-1",
"ancestors":[
{
"_id":"40ce077e90c6262bdc21aa44",
"label":"label 1"
}
]
},
{
"_id":"40ce077e90c6262bdc21aa44",
"parent":null,
"label":"label 1",
"ancestors":[]
}
]
}
This is the schema:
const categorySchema = new mongoose.Schema(
{
label: {
type: String,
required: true
},
parent: {
type: ObjectId,
default: null,
ref: 'category'
},
ancestors: [
{
_id: {
type: ObjectId,
ref: 'category'
},
label: String
}
]
},
{ timestamps: true }
);
I tried to do this:
async getDescendants(req, res) {
let { pId } = req.body;
if (!pId) {
return res.json({ error: 'All filled must be required' });
} else {
try {
const data = await patternModel
.find({ 'ancestors._id': pId })
.select({
_id: false,
label: true
})
.exec();
if (data) {
return res.json({ data });
}
} catch (err) {
return res.json({ err: err });
}
}
}
this is my actual result:
{
"data": []
}
when I change .find({ 'ancestors._id': pId }) to .find({ 'ancestors.label': label }) it works but not for the id.
It is not a simple field. It is an array of subdocuments. Use elemMatch.
Edit: When querying _id fields you will have to wrap convert them into ObjectIds (specific to Mongo).
let newPid = mongoose.Types.ObjectId(pId);
const data = await patternModel.find({ ancestors: { $elemMatch : { _id: newPid} } })
.select({ _id: false,label: true })
.exec();

change bool value mongodb

m beginner at react i have a little problem i want to change a bool value which is isApproved so the admin click a button and approve the post so it can be displayed here is my code . can anyone help me
this is the function that change the value of isApproved
//#route put api/posts/approve/:id
//#desc approve post
//#access Private
router.post('/:id/approve', auth, async(req, res) => {
console.log("action base de donne begin");
Post.findById(req.params.id, (err, post) => {
console.log(post.isApproved);
if (err) {
console.log(err);
} else if (post.isApproved == false) {
post.update({$set: {isApproved: true}});
} else {
post.update({$set: {isApproved: false}});
}
});
});
the post model :
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
// Create Schema
const PostSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
text: {
type: String,
required: true
},
name: {
type: String
},
avatar: {
type: String
},
isApproved: {
type: Boolean,
default: false
},
likes: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'users'
}
}
],
comments: [
{
user: {
type: Schema.Types.ObjectId,
ref: 'users'
},
text: {
type: String,
required: true
},
name: {
type: String
},
avatar: {
type: String
},
date: {
type: Date,
default: Date.now
}
}
],
date: {
type: Date,
default: Date.now
}
});
module.exports = Post = mongoose.model('post', PostSchema);
approve action :
// Approve Approve
export const approve = id => async dispatch => {
try {
console.log('action is begin');
console.log(id);
const res = await axios.post(`/api/posts/${id}/approve`);
console.log('la valeur dans action est',res)
dispatch({
type: APPROVE_POST,
payload: { id, isApproved: res.data }
});
} catch (err) {
dispatch({
type: POST_ERROR,
payload: { msg: err.response.statusText, status: err.response.status }
});
}
};
post reducers
import {
GET_POSTS,
POST_ERROR,
UPDATE_LIKES,
DELETE_POST,
ADD_POST,
GET_POST,
ADD_COMMENT,
REMOVE_COMMENT,
APPROVE_POST
} from '../actions/types';
const initialState = {
posts: [],
post: null,
loading: true,
error: {}
};
export default function(state = initialState, action) {
const { type, payload } = action;
switch (type) {
case GET_POSTS:
return {
...state,
posts: payload,
loading: false
};
case GET_POST:
return {
...state,
post: payload,
loading: false
};
case ADD_POST:
return {
...state,
posts: [payload, ...state.posts],
loading: false
};
case DELETE_POST:
return {
...state,
posts: state.posts.filter(post => post._id !== payload),
loading: false
};
case POST_ERROR:
return {
...state,
error: payload,
loading: false
};
case UPDATE_LIKES:
return {
...state,
posts: state.posts.map(post =>
post._id === payload.id ? { ...post, likes: payload.likes } : post
),
loading: false
};
case APPROVE_POST:
return {
...state,
posts: state.posts.map(post =>
post._id === payload.id ? { ...post, isApproved: payload.isApproved } : post
),
loading: false
};
case ADD_COMMENT:
return {
...state,
post: { ...state.post, comments: payload },
loading: false
};
case REMOVE_COMMENT:
return {
...state,
post: {
...state.post,
comments: state.post.comments.filter(
comment => comment._id !== payload
)
},
loading: false
};
default:
return state;
}
}
case APPROVE_POST:
return {
...state,
posts: state.posts.map(post =>
post._id === payload.id ? { ...post, isApproved: payload.isApproved } : post
),
loading: false
};
{ "$eq": [ false, "$isApproved" ] } will return true or false
db.collection.update(
{},
[ { "$set": { "isApproved": { "$eq": [ false, "$isApproved" ] } } } ]
);
Use findByIdAndUpdate
Demo - https://mongoplayground.net/p/4kCEaEpuIko
i change the code to this but i always have a false value
router.post('/:id/approve', auth, async(req, res) => {
console.log("action base de donne begin");
Post.findById(req.params.id, (err, post) => {
console.log(post.isApproved);
if (err) {
console.log(err);
} else if (post.isApproved == false) {
post.update(
{},
[ { "$set": { "isApproved": { "$eq": [ true, "$isApproved" ] } } } ]
);
} else {
post.update(
{},
[ { "$set": { "isApproved": { "$eq": [ false, "$isApproved" ] } } } ]
);
}
});
});

Why pull is not removing elements

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;
}
};

insert document in bulk using for loop mongoose

Why this won't insert 20 document for me?
for (let i = 0; i <= 20; i++) {
const [updated] = await Promise.all([
Job.findOneAndUpdate(
{ _id: id },
{
$set: {
status: 'something'
}
},
{ upsert: true, new: true }
),
User.findOneAndUpdate(
{ _id: userId },
{
$set: { assigned: true }
},
{ upsert: true, new: true }
)
])
}
or I should use reduce and Promise resolve? Above query worked just that it doesn't insert 20 documents, it inserted one document.
If you have array of id then you can use bulkWrite
const id = ['844646464', '45646546546', '45646546546']
Model.bulkWrite(
req.body.idArray((id) => {
return ({
updateOne: {
filter: { _id: id },
update: { $set: { status: 'something' } },
upsert: true
}
})
})
})
It will create a request something like this
bulkWrite([
{ updateOne: { filter: { _id: id }, update: { $set: { status: 'something' } } },
{ updateOne: { filter: { _id: id }, update: { $set: { status: 'something' } } },
{ updateOne: { filter: { _id: id }, update: { $set: { status: 'something' } } }
])
Which efficiently performs all updates in a single request to the server with a single response.

Resources