I already took a look into the question that people keep saying this question is duplicated to, but I couldn't figure out how to deal with it with my code. I need an explanation. Thank you
I'm new to paypal APIs so I'm kind of confused right now. creating transaction only works when I don't specify payee property, but how would paypal know who to send the money when there's no payee specified?
Here's the code
$(function() {
paypal.Button.render({
env: 'sandbox', // Or 'sandbox'
client: {
sandbox: 'xxxxxx',
production: 'xxxxxx'
},
commit: false, // Show a 'Pay Now' button
payment: function(data, actions) {
return actions.payment.create({
payment: {
transactions: [
{
amount: { total: '5.00', currency: 'USD' },
description: "TEST",
payee: { email: "seller-inventory#gmail.com" }
}
]
}
});
},
onAuthorize: function(data, actions) {
return actions.payment.execute().then(function(payment) {
console.log("payment", payment)
});
}
}, '#paypal');
})
Error code:
In the transaction object you need to have the items list with the items you are trying to sell. The mail also needs to exist.
If you don't specify the mail paypal send the money to whom has generated the client id key.
Also the items sum and currenct needs to match with the amount sum and currency
Try this (change sandbox id and the payee email need to exist in paypal):
$(function() {
paypal.Button.render({
env: 'sandbox', // Or 'sandbox'
client: {
sandbox: 'yourclientid',
production: 'xxxxxx'
},
commit: false, // Show a 'Pay Now' button
payment: function(data, actions) {
return actions.payment.create({
payment: {
transactions: [
{
amount: { total: '5.00', currency: 'USD' },
payee: { email: "seller-inventory#gmail.com" },
item_list: {
items: [
{
name: "hat",
sku: "1",
price: "5.00",
currency: "USD",
quantity: "1",
description: "Brown hat."
}]}
}
]
}
});
},
onAuthorize: function(data, actions) {
return actions.payment.execute().then(function(payment) {
console.log("payment", payment)
});
}
}, '#paypal');
})
Related
I have been trying to find the averageSum and averageRating, but I cannot get it done because I do not know how to populate using aggregate or if there is a work around. I have heard of $lookup, but I am not sure how to do it, also it tells me something about atlas tier does not do it. Is there a another way around to this? Can I populate then aggregate or can I find the averageSum and averageRating at the end using another method? Please help me
here is how my schema looks:
const favoriteSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
unique: true,
},
favoriteSellers: [
//create array of object id, make sure they are unique for user not to add multiple sellers
{
type: mongoose.Schema.Types.ObjectId,
ref: "Seller",
unique: true,
},
],
});
and here is my Seller schema:
const sellerSchema = new mongoose.Schema({
user: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
unique: true,
},
business: businessSchema,
sellerType: [String],
reviews: [
{
by: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
unique: true,
},
title: {
type: String,
},
message: {
type: String,
},
rating: Number,
imagesUri: [String],
timestamp: {
type: Date,
default: Date.now,
},
},
],
...
});
So I have an array of favorite sellers, I want to populate the sellers, then populate the reviews.by and user paths, and then do the calculation for the average sum and do the average rating. If possible please help me. What are my options here? Just do it outside on the expressjs route logic?
Here is my aggregate:
aggregatePipeline.push({
$match: { user: req.user._id },
});
//****** Here is where I want to populate before start the rest **********
then continue to following code because the fields(paths) are not populated so it averageSum will be 0 at all times.
aggregatePipeline.push({
$addFields: {
ratingSum: {
$reduce: {
initialValue: 0,
input: "$favoriteSellers.reviews",
in: { $sum: ["$$value", "$$this.rating"] },
},
},
},
});
//get average of rating ex. seller1 has a 4.5 averageRating field
aggregatePipeline.push({
$addFields: {
averageRating: {
$cond: [
{ $eq: [{ $size: "favoriteSellers.reviews" }, 0] }, //if it does not have any reviews, then we will just send 0
0, //set it to 0
{
$divide: ["$ratingSum", { $size: "$reviews" }], //else we can divide to get average Rating
},
],
},
},
});
let favList = await Favorite.aggregate(aggregatePipeline).exec();
When I retrieve my code, the array looks like:
[
{
_id: new ObjectId("62a7ce9550094eafc7a61233"),
user: new ObjectId("6287e4e61df773752aadc286"),
favoriteSellers: [ new ObjectId("6293210asdce81d9f2ae1685") ],
}
]
Here is a sample on how I want it to look:
(so each seller should have a field of average rating like and averageSum)
_id: 'favorite_id.....'
user: 'my id',
favoriteSellers:[
{
_id: 'kjskjhajkhsjk',
averageRating: 4.6
reviews:[.....],
...
},
{
_id: 'id______hsjk',
averageRating: 2.6
reviews:[.....],
...
},
{
_id: 'kjid______khsjk....',
averageRating: 3.6
reviews:[.....],
...
}
]
I am trying to do a transact write in DynamoDB. I can't seem to see the error and the error says "validationError, none" which isn't particualarly helpful. The Put for sure works but I am keeping here for completeness in the example
await dynamoDb.transactWrite({
TransactItems: [
{
Put: {
TableName: process.env.TABLE_NAME,
Item: {
pk: compoundId,
sk: interest,
gsi1pk: "#INTEREST",
interest: interest,
id,
},
},
},
{
Update: {
ExpressionAttributeValues: {
":num": 1,
":initial": 0,
},
ExpressionAttributeNames: {
"#tally": "tally",
},
Key: {
PK: shop,
SK: interest,
},
TableName: process.env.TABLE_NAME,
UpdateExpression:
"SET #tally = if_not_exists(tally, :initial) + :num",
},
},
],
});
I'm fairly confident that this is doable per these similar solved questions here:
ItemCollectionMetrics is empty after successful transactWrite using DynamoDB.DocumentClient
Increment the value if it exists, else add a new entry in DynamoDB
The following appears to have worked and the error was adding the ExpressionAttributeNames
await dynamoDb.transactWrite({
TransactItems: [
{
Put: {
TableName: process.env.TABLE_NAME,
Item: {
pk: compoundId,
sk: interest,
gsi1pk: "#INTEREST",
watching: watching,
interest: interest,
id,
},
},
},
{
Update: {
ExpressionAttributeValues: {
":num": 1,
":initial": 0,
},
Key: {
pk: shop,
sk: interest,
},
TableName: process.env.TABLE_NAME,
UpdateExpression:
"SET tally = if_not_exists(tally, :initial) + :num",
},
},
],
});
I am attempting to create a PayPal checkout order on my Vue site. I am currently passing two props to the component as well as two data objects
props: {
price: Number,
shipping: Number,
},
data() {
return {quantity: 1, switches: 'red'}
},
I am referencing these four variables in my code as this.price, this.shipping etc. I have confirmed these are all valid
I am attempting to access these inside a method but this is being over-ridden and all four of these are undefined.
I still don't quite understand this, but I was under the impression that using an arrow function as I have done should stop this from changing. Is this not the case?
Code
await paypal.Buttons({
style: {
layout: 'vertical',
color: 'black',
shape: 'pill',
},
createOrder: (data, actions) => {
return actions.order.create({
purchase_units: [{
amount: {
currency_code: "USD",
value: ((this.price + this.shipping) * this.quantity).toString(),
breakdown: {
item_total: { /* Required when including the `items` array */
currency_code: "USD",
value: this.price.toString()
},
shipping: {
currency_code: "USD",
value: this.shipping.toString()
}
}
},
items: [
{
name: "First Product Name", /* Shows within upper-right dropdown during payment approval */
description: "Optional descriptive text..", /* Item details will also be in the completed paypal.com transaction view */
unit_amount: {
currency_code: "USD",
value: this.price.toString()
},
quantity: this.quantity.toString
},
]
}]
});
},
}).render('#paypal-button-container')
Enroll.updateOne(
{
"reviewers._id": userID,
},
{
$set: {
"reviewers.$.scores": req.body.scores,
},
},
(errUpdate, resultUpdate) => {
if (errUpdate) {
return res.status(500).json({ success: false, error: errUpdate });
} else {
return res.status(200).json({ success: true, data: resultUpdate });
}
}
);
I'm new to mongodb. Above is a function within an api that is used to update certain data.
The schema of Enroll would look like this:
[
{
_id: xxxxx,
otherdata: xxxx,
reviewers: [ { _id: xxxx, otherdata: xxxx } , { _id: xxxx2, otherdata: xxxx2 } ]
},
{
second enroll item...
}
]
but when I called the api, it returns n:0 which indicates no match is found. Am I missing some steps here?
I'm trying to update a value inside my array of objects.
Looking at the above mongoDB schema what I want is:
Find an expense with the ID match with the _id and need to update the fields with new ones from the req.body.
Just need to update the: expensesType, description, price and status.
The following code is what I tried to do.
First I need to match the right expense and it works fine but when I try to house.save() show me a message 'house.save is not a function'. So I think maybe I need to use a mongoDB function to get the result.
router.put("/editExpense/:id", ensureAuthenticated, (req, res) => {
var id = mongoose.Types.ObjectId(req.params.id);
House.find(
{ "expensesHouse._id": id },
{
members: 1,
name: 1,
description: 1,
address: 1,
type: 1,
user: 1,
userID: 1,
userType: 1,
expensesHouse: { $elemMatch: { _id: id } },
date: 1
}
).then(house => {
console.log(house);
expenseType = req.body.expenseType;
description = req.body.description;
price = req.body.price;
status = req.body.status;
house.save().then(() => {
req.flash("success_msg", "Expenses Updated");
res.redirect("/houses/dashboard");
});
});
});
****** UPDATED ******
After a search I found this updateOne and after adjusts, this is my final result but this way I delete every record..
router.put("/editExpense/:id", ensureAuthenticated, (req, res) => {
var id = mongoose.Types.ObjectId(req.params.id);
House.updateOne(
{ "expensesHouse._id": id },
{
members: 1,
name: 1,
description: 1,
address: 1,
type: 1,
user: 1,
userID: 1,
userType: 1,
expensesHouse: { $elemMatch: { _id: id } },
date: 1
},
{ $set: { "expensesHouse.expenseType": req.body.expenseType } }
).then(house => {
req.flash("success_msg", "Expenses Updated");
res.redirect("/houses/dashboard");
});
});
*********** RESOLUTION ***********
I just fixed the problem the way I show below.
House.updateOne(
{ "expensesHouse._id": id },
{
$set: {
expensesHouse: {
expenseType: req.body.expenseType,
description: req.body.description,
price: req.body.price,
status: req.body.status
}
}
}
You are really close to the answer the problem right now that you are having is syntax difference between find and UpdateOne
This is what Find expects, Check MongoDB docs
db.collection.find(query, projection)
This is what updateOne expects, Check Mongo docs
db.collection.updateOne(
<filter>,
<update>,
{
upsert: <boolean>,
writeConcern: <document>,
collation: <document>,
arrayFilters: [ <filterdocument1>, ... ],
hint: <document|string> // Available starting in MongoDB 4.2.1
}
)
See the Difference? Second parameter should be update not projection because Update one
returns
matchedCount containing the number of matched documents
modifiedCount containing the number of modified documents
upsertedId containing the _id for the upserted document.
A boolean acknowledged as true if the operation ran with write concern or false if write concern was disabled.
So Your code should be
House.updateOne(
{ "expensesHouse._id": id },
{ $set: { "expensesHouse.expenseType": req.body.expenseType } }
).then(house => {
req.flash("success_msg", "Expenses Updated");
res.redirect("/houses/dashboard");
});
});
House.findOneAndUpdate({userId : req.params.userId},
{ $set: { "expensesHouse.$[element].status": req.body.status } },
{ multi:true, arrayFilters: [{ "element.userID" : req.params.subUserId }], new:true })
Your Api reuquest consist of both the IDs (outer as well as inner) like /api/update/:userId/:subUserId