Mongoose document.updateOne() not working as expected - node.js

code
Hi, I am trying to update my document using document.updateOne() in mongoose but only the balance field, downlines,
const username = req.params.username;
try {
const partner = await Partner.findOne({ username });
await partner.updateOne({ isApproved: true });
const ref = await Partner.findOne({ username: partner.referer });
if (ref) {
await ref.updateOne(
{
$inc: { points: 10 },
referer: partner.referer,
$inc: { earnings: 10 },
$inc: { balance: 10 },
$push: { downlines: partner.username },
},
{ new: true }
);
const grandRef = await Partner.findOne({ username: ref.referer });
if (!grandRef) {
res
.status(200)
.json(
'Partner approval was successfull with a referrer but no grand referrer'
);
} else {
await grandRef.updateOne(
{
$inc: { points: 3 },
grandReferer: ref.referer,
$inc: { earnings: 3 },
$inc: { balance: 3 },
$push: { grandDownlines: partner.username },
},
{ new: true }
);
res
.status(200)
.json(
'Partner approval was successfull with both referrer and grand referrer'
);
}
} else {
res
.status(200)
.json(
'Partner approval was successfull without a referrer or a grand referrer'
);
}
} catch (err) {
res.status(500).json('Something went wrong');
console.log(err);
}
and grand_downlines updates but the earnings and points do not. Please check my snippet in the attached image and help.

Okay so I just realized because I am using "$inc" more than one at the same time and if I change the positions, the last "$inc" updates so I used expressions.
{
$push: { downlines: partner.username },
points: ref.points + 10,
balance: ref.balance + 10,
earnings: ref.earnings + 10,
},
{ new: true }

Related

mongoose findOneAndUpdate gives different user

I was trying to $pull an object inside my cart collections. but after I make a request and sent a specific _id it gives me a different person.
this was the _id I sent from my client side.
{ id: '62a849957410ef5849491b1b' } /// from console.log(req.params);
here's my mongoose query.
export const deleteItem = (req,res) => {
const { id } = req.params;
console.log(id);
try {
if(!mongoose.Types.ObjectId.isValid(id)) return res.status(404).json({ message: 'ID not found' });
ClientModels.findOneAndUpdate(id, {
$pull: {
cart: {
product_identifier: req.body.cart[0].product_identifier
}
}
},{
new: true
}).then(val => console.log(val)).catch(temp => console.log(temp));
} catch (error) {
res.status(404).json(error);
}
}
after the request here's the callback.
{
_id: new ObjectId("62a77ab16210bf1afd8bd0a9"),
fullname: 'Gino Dela Vega',
address: '008 Estrella.st santo cristo',
email: 'gamexgaming1997#gmail.com',
google_id: 'none',
birthday: '1997-12-30',
number: 9922325221,
gender: 'Male',
username: 'ginopogi',
password: '$2b$12$YCc1jclth.ux4diwpt7EXeqYyLOG0bEaF.wvl9hkqNVptY.1Jsuvi',
cart: [],
wishlist: [],
toBeDeliver: [],
Delivered: [],
__v: 0
}
as you guys can see after sending a specific _id to find a user...the callback gives me a different user reason that I can't pull the specific object inside cart. (the object I was trying to pull is on another user)
Probably because findOneAndUpdate expect a filter as first parameter, try to switch to findByIdAndUpdate if you want to filter by a specific _id:
export const deleteItem = (req, res) => {
...
ClientModels.findByIdAndUpdate(
id,
{
$pull: {
cart: {
product_identifier: req.body.cart[0].product_identifier,
},
},
},
{
new: true,
}
)
.then((val) => console.log(val))
.catch((temp) => console.log(temp));
} catch (error) {
res.status(404).json(error);
}
};

'MongooseError: Callback must be a function, got [object Object]' When using "updateMany" function

Ignore the messy code. I've been working for hours on end and haven't had time to organize it.
I keep getting this error everytime the messageCount is 100 or more.
const profileData = await Profiles.findOne({
userID: message.author.id
});
if (!profileData) return console.log('re')
try {
if (profileData.messageCount >= 100) {
console.log('yeet')
await Profiles.updateMany({
userID: message.author.id
}, {
messageCount: 0,
}, {
$inc: {
caseCount: +1
}
}, {
upsert: true
});
} else {
console.log('na')
}
} catch (error) {
console.log(error);
}
The updateMany() method needs only 3 parameters, it expects the fourth parameter to be an optional callback function, but you used an object, which explains the error message.
Combine your set and inc parameters like this:
await Profiles.updateMany(
{
userID: message.author.id
},
{
$set: { messageCount: 0 },
$inc: { caseCount: 1 },
},
{
upsert: true
}
);
Check the docs for more information.

Sort in mongoose-aggregate-paginate-v2

I am using mongoose-aggregate-paginate-v2
and sort does not work
var aggregate = searchmodel.aggregate()
aggregate.match({ word: { $regex: `.*${word}.*` } })
.group({
_id: '$user_id', doc: { $first: '$$ROOT' }
})
var options = {
page: page, limit: 50, sort: { createdAt: -1 }
}
searchmodel.aggregatePaginate(aggregate, options).then(function (results) {
return res.json(results)
}).catch(function (err) {
console.log(err);
})
I tried lot of things for sort but it does not work at all
You should write,
var aggregate = searchmodel.aggregate()
aggregate.match({ word: { $regex: `.*${word}.*` } })
.group({
_id: '$user_id', doc: { $first: '$$ROOT' }
})
var options = {
page: page, limit: 50, sort: { createdAt: 'desc' }
}
searchmodel.aggregatePaginate(aggregate, options).then(function (results) {
return res.json(results)
}).catch(function (err) {
console.log(err);
})
Actually I found the solution to the problem.
You need to add _id to the sort object.
Example:
const options = {
page: page,
limit: limit,
sort: { _id: 1, createdAt: -1 },
};
and it works.

MongoDB Mongoose How to delete an object from an array

var UserSchema = new mongoose.Schema({
//Irrelevant code
profile:
{
requests: [{ sender: String, id: String, hasSelected: Boolean, value: Boolean}]
}
});
That object is to keep track of friend request, I want it to get completely deleted from the requests array once it has been accepted or declined. I have tried a whole bunch of stuff but nothing is deleting it. Currently have this code:
User.updateOne({ id: user.id },
{ "$pull": { "profile": { "requests": { "id": targetId } } } },
{ "multi": true },
function(err,status) {
if(err){console.log("Could not delete the friend request");}
else{
console.log("Sucessfully deleted friend request from: " + user.name);}
}
);
It always says it was deleted on the log, but when I check on mongoDB the request is still there.
try $elemMatch to remove the specific object.
User.updateOne(
{ id: user.id },
{ $pull: { "profile.requests": { $elemMatch: { id: targetId } } } },
{ multi: true },
function (err, status) {
if (err) {
console.log("Could not delete the friend request");
} else {
console.log("Sucessfully deleted friend request from: " + user.name);
}
}
);

Is there any way to rename the path while we select the complex object from mongodb using mongoose in nodejs?

I want to rename the path of the fields which are coming from the response.
My Query:
const allLeads = await Lead.find().select({
"basic.mobileNumber": 1
});
res.send({ allLeads });
Response I'm Getting
{
"allLeads": [
{
"_id": "5d9f0e2118d1a445bae077aa",
"basic": {
"mobileNumber": "1223654789"
}
},
{
"_id": "5d9f16a8cba7744902acb422",
"basic": {
"mobileNumber": "1123654789"
}
}
]
}
how I want the response
{
_id: 5d9f0e2118d1a445bae077aa,
mobileNumber: "1223654789"
},
{
_id: 5d9f16a8cba7744902acb422,
mobileNumber: "1123654789"
}
So is there any way yo archive this using mongoose?
I did it like this. Is there any other and better way to do this?
let simpleLeadInfo = [];
await SwatiLead.find()
.select({
_id: 1,
"basic.mobileNumber": 1,
})
.exec((err, data) => {
if (!err) {
for (lead in data) {
const obj = {
id: data[lead]._id,
mobileNumber: data[lead].basic.mobileNumber,
};
simpleLeadInfo = [...simpleLeadInfo, obj];
}
return res.send({ error: false, status: "OK", simpleLeadInfo });
}
});

Resources