I want to update and pull users from array using Mongodb. i'm updating users in array successfully and checking the length of users. if users are more than or equal to 2, i want to slice the first 2 users and to remove first 2 users from array using pull method. example stranger chat connect ( connecting two users when they pressed connectstranger button )
var userName = req.body.userName
connection.connectedusers.updateMany({}, { $push: { connectArray: [userName] } }, { upsert: true }, function (err, docs) {
if (err) {
console.log(err);
} else {
connection.connectedusers.find({}, async (err, list) => {
if (err) {
console.log(err);
}
else {
setTimeout(async () => {
if (list[0].connectArray.length >= 2) {
clearTimeout();
var shortListed = list[0].connectArray.slice(0, 2);
console.log(shortListed,'shortlisted array')
try {
await connection.connectedusers.update({},
{ $pull: { connectArray: { $in: shortListed } } },
{ multi: true }
)
const docs = await connection.connectedusers.find({});
res.json({
message: 'users selected successfully',
status: 1,
docs: docs
});
} catch (err) {
res.status(201).json(err);
}
} else {
const docs = await connection.connectedusers.find({});
console.log(docs, 'docs')
const allUsers = docs.connectArray;
console.log(allUsers, 'allUsers')
await connection.connectedusers.update({},
{ $pull: { connectArray: { $in: allUsers } } },
{ multi: true }
)
res.json({
message: 'users not selected',
status: 2,
docs: docs,
allUsers: allUsers
})
}
}, 10000);
}
});
}
})
For the first post request am getting status 2 error : users not selected, but i want it to be wait for some time. once the array count increased to 2.. need to slice it and pull the selected users from array.
from How to update and pull users using mongodb and node js
No comments:
Post a Comment