I am trying to verify the user by taking the secrettoken from the link sent in the email. I am able to extract the secrettoken but not able to update the value of active as true.
Below is my code
router.route('/verify')
.get((req,res)=>{
console.log('request recieved');
const token = req.query.id;
User.updateOne(
{ secretToken: token },
{
$set: { price: true }
},function(err,res){
if(err){
throw err;
}
else{
console.log('one document updated');
}
}
);
});
"email": "surendrap720#gmail.com",
"username": "surendrap720",
"password": "$2a$10$UEKSpPpVWfZ3urclkayW6OcAUvscBrql23WU6fvfbI0Nd1jzo2Bxa",
"type": "tutor",
"secretToken": "5A6fXVh5gEObwUQxgpG4DpJ85COMJveJ",
"active": false,
You are not modifying active at all in your updateOne code.
change this:
$set: { price: true }
to this:
{ active: true }
Related
when i am creating subscription through stripe it gives err message
As i am doing subscription through stripe
i am also giving some msg about authentication in dashboard like 3d secure authenticatio.
and my cvc_check is unavailable in showing dashboard
1.first issue is 3d secure authentication.
2.cvc check unavailbel in India.
My account is also india
TypeError: stripe.confirmCardPayment is not a function
my code is pls what i am doing wrong
stripe.customers.create(
{
name: name,
email: email,
phone: reqObj.phone,
address: { "city": reqObj.address, "country": "IN",
"line1": "", "line2": "", "state":"India" },
},
function (err, customer) {
if (err) {res.json({ "status": false, "error": err })
console.log(err)
}else {
customer_id=customer.id;
stripe.tokens.create(
{
card: {
number: reqObj.card_no,
exp_month: reqObj.exp_month,
exp_year: reqObj.exp_year,
cvc: reqObj.cvc
},
},
function (err, token) {
if (err) {
res.json({ "status": false, "errorT": err})
} else {
// stripe.customers.createSource(
// customer_id,
// { source: token.id },
// function (err, card) {
// if (err) {
// res.json({ status: "false", "error": err })
// }else {
stripe.plans.list(
{ product: "prod_IMGu6PI2mJbBCi", active: true },
function (err, plans) {
if (!err) {
for(i in plans.data){
if(plans.data[i].amount==reqObj.amount){
var myId=plans.data[i].id
stripe.paymentMethods.create({
type: 'card',
card: {
number: reqObj.card_no,
exp_month: reqObj.exp_month,
exp_year: reqObj.exp_year,
cvc: reqObj.cvc
},
},function(err,result){
// console.log(err,result)
stripe.paymentMethods.attach(result.id, {
customer: customer_id,
},function(err,result1){
// console.log(err,"result1",result1)
stripe.customers.update(
customer_id,
{
invoice_settings: {
default_payment_method: result.id,
},
},function(err,res2){
// console.log(err,"res2")
stripe.subscriptions.create({
customer: customer_id,
items: [{ price: myId}],
expand: ['latest_invoice.payment_intent'],
},function(err,res3){
console.log(err,"res3",
res3.latest_invoice.payment_intent.client_secret)
a=res3.latest_invoice.payment_intent.client_secret
stripe.confirmCardPayment(
res3.latest_invoice.payment_intent.client_secret,
function(err,paymentIntent)
{
console.log(err,"paymentIntent",paymentIntent)
}
)}
);
} );
});
});
}
});
}
// asynchronously called
});
Your code is mixing up client-side and server-side code together which will not work. The stripe.confirmCardPayment() method comes from Stripe.js and should be called client-side in Javascript inside the browser, not server-side with Node.js.
The beginning of your code is updating a Customer with the right default payment method id. Then it's creating a Subscription. And then, if the creation fails to have the first invoice paid, for example if the card is declined or requires 3D Secure, you have to then go back to the client, in the browser, to run the next step which is to confirm the PaymentIntent associated with the Subscription's Invoice.
So you need to go back to the client, where you originally created the PaymentMethod id pm_123456 that you passed in result.id and then try to confirm the PaymentIntent.
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);
}
}
);
I'm trying to validate who can do a PUT request on a document.
I have a field that indicates who created the document. If the user created it he/she can edit it and this part is working correctly.
I also have an array of user ids that should also be able to edit but I can't seem to be able to check if the current user is in this array and therefore I can't edit the document.
Here's one document:
{
"teachers": ["5c740f96e0d6b10016801daa"],
"_id": "5cd552b179b1b30016c4c0e9",
"date": "2019-05-10T10:30:09.978Z",
"name": "prof",
"goal": "goal",
"activity": {
"affective_objectives": [],
"social_objectives": [],
"_id": "5cd552b179b1b30016c4c0ea",
"learning_objectives": [
{
"_id": "5cd552b179b1b30016c4c0eb",
"knowledge_category": "Factual",
"behaviour": "teste",
"subject_matter": "asdas",
"conditions": "",
"degree": ""
}
],
"description": "des",
"subject": "subj",
"delivery_mode": "teste",
"interaction": "teste",
"scope": "teste",
"age": 5,
"feedback_use": "High",
"interrelationship": "High",
"motivation": "High",
"participation": "High",
"performance": "None"
},
"project_manager": "5cb48f6a169a9b0016d34dac",
"__v": 0
}
And my PUT function:
function edit(req, res) {
let query = {
_id : req.params.id
};
Projeto.findById(query)
.then(async (projeto) => {
if(!projeto) {
return res.status(404).json({error: 'not_found', message: 'This project doesn\'t exist.'});
}
if ( (projeto.project_manager != req.user._id) && (projeto.teachers.indexOf(req.user._id) != -1) ) {
return res.status(403).json({error: 'forbidden', message: 'You can\'t edit this project.'});
} else {
await Projeto.findOneAndUpdate(query, req.body, {new: true});
res.json({ message: 'Project successfully edited.'});
}
})
.catch(utils.handleError(req, res));
}
If I try to do a PUT request with the project_manager user everything works but with the user in "teachers" I get the error message that I can't edit.
What's the correct way to verify that here?
If the user is not in teachers array the indexOf() method will return -1.
So, you need to check if it's the case for you:
function edit(req, res) {
let query = {
_id : req.params.id
};
Projeto.findById(query)
.then(async (projeto) => {
if(!projeto) {
return res.status(404).json({error: 'not_found', message: 'This project doesn\'t exist.'});
}
if ( (projeto.project_manager != req.user._id) && (projeto.teachers.indexOf(req.user._id) === -1) ) {
return res.status(403).json({error: 'forbidden', message: 'You can\'t edit this project.'});
} else {
await Projeto.findOneAndUpdate(query, req.body, {new: true});
res.json({ message: 'Project successfully edited.'});
}
})
.catch(utils.handleError(req, res));
}
TLDR:
Replace projeto.teachers.indexOf(req.user._id) != -1 by projeto.teachers.indexOf(req.user._id) === -1
I am using Loopback 3.0 with MongoDB connector.
In a REST method exposed somewhere, I need to access the currently logged user and make some updates on it.
I have extended the base User model, calling it appUser, the login works, and I can get the token (after I changed the token model to point to the appUser) of a logged user. The model is the following one:
{
"name": "appUser",
"plural": "appUsers",
"base": "User",
"idInjection": true,
"options": {
"validateUpsert": true
},
"properties": {
"gender": {
"type": "string",
"enum": [
"M",
"F"
]
},
"birthDate": {
"type": "Date"
}
},
"validations": [],
"relations": {},
"acls": []
}
I need to access the user profile, in order to update it. But when I query it, I get null as result.
const User = app.models.appUser;
User.findOne({
where: {
_id: ObjectId("5aae7ecd2ed1b11b1c09cf25")
}
}, (err, user) => {
if (err || res == null) {
console.log("Error updating the user ");
const error = {
"name": "Database error",
"status": 500,
"message": "Can't access the database."
}
callback(error, null, null);
} else {
//Whatever
}
});
But if I run the same query from Robo3T on MongoDB, it works.
db.getCollection('appUser').find({"_id": ObjectId("5aae7ecd2ed1b11b1c09cf25")})
What am I doing wrong?
Thank you,
Massimo
You didn't call the user so that should be the case, also in your callback you are passing null and not your user result. However I don't get where the res variable came from.
const User = app.models.appUser;
User.findOne({
where: {
_id: ObjectId("5aae7ecd2ed1b11b1c09cf25"),
}
}, (err, user) => {
if (err) {
console.log("Error updating the user", err); // logs the app error
const error = {
"name": "Database error",
"status": 500,
"message": "Can't access the database."
}
callback(error, null); // passes your custom error
}
console.log("APP USER", user);
callback(null, user);
});
I don't how you calling your callback but i think you can manage this.
If you still have no result try changing _id to id
I am building a Node.js express RESTfull API using Mongodb and mongoose.
This is my schema:
var UserSchema = new mongo.Schema({
username: { type: String },
password: { type: String, min: 8 },
display_name: { type: String, min: 1 },
friends: { type: [String] }
});
UserSchema.post('remove', function(next){
console.log({ friends: this._id }); // to test if this gets reached (it does)
UserSchema.remove({ friends: this._id });
});
And this is the function that removes a User:
.delete(function(req, res) {
User.findById(req.params.user_id, function(err, user) {
if (err) {
res.status(500);
res.send(err);
} else {
if (user != null) {
user.remove();
res.json({ message: 'User successfully deleted' });
} else {
res.status(403);
res.json({ message: 'Could not find user.' });
res.send();
}
}
});
});
What I need to do is when a user is removed, his or her _id (String) should also be removed from all the other users' friends array. Hence the remove hook in the schema.
Right now the user gets deleted and the hook gets triggered, but the user _id is not removed from the friends array (tested with Postman):
[
{
"_id": "563155447e982194d02a4890",
"username": "admin",
"__v": 25,
"password": "adminpass",
"display_name": "admin",
"friends": [
"5633d1c02a8cd82f5c7c55d4"
]
},
{
"_id": "5633d1c02a8cd82f5c7c55d4",
"display_name": "Johnybruh",
"password": "donttouchjohnsstuff",
"username": "John stuff n things",
"__v": 0,
"friends": []
}
]
To this:
[
{
"_id": "563155447e982194d02a4890",
"username": "admin",
"__v": 25,
"password": "adminpass",
"display_name": "admin",
"friends": [
"5633d1c02a8cd82f5c7c55d4"
]
}
]
To try and figure it out I have looked at the Mongoosejs Documentation, but the mongoose doc example doesn't cover the remove hook. Also this stackoverflow qestion but this question seems to be about removing from other schemas.
I think i'm doing the remove in the hook wrong, but I can't seem to find the problem.
Thanks in advance!
EDIT:
I could not get the first suggestion by cmlndz to work, so I ended up fetching all the documents with arrays that contained the to-be-deleted users' id and pulling it from them one-by-one:
The delete function now contains this bit of code that does the magic:
// retrieve all documents that have this users' id in their friends lists
User.find({ friends: user._id }, function(err, friends) {
if (err) {
res.json({ warning: 'References not removed' });
} else {
// pull each reference to the deleted user one-by-one
friends.forEach(function(friend){
friend.friends.pull(user._id);
friend.save(function(err) {
if (err) {
res.json({ warning: 'Not all references removed' });
}
});
});
}
});
You could use $pull to find all documents that contain the "ID" in the "friends" array -or- find any matching document and popping the "ID" out of the array one by one.