Cannot update or save data on second or next user in mongodb - database

May I know what is the problem with my code for the backend. I try to create a place and update it in the user database. The problem is If I only have 1 user. The database can create and update the data but if I have more than 2 then, the data cannot be updated or created. Here is my code. I have been working on this part for so long, that I cannot find the solution.
const createFile = async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return next(
new HttpError('Invalid inputs passed, please check your data.', 422)
);
}
const { userId, Dataset } = req.body;
const createdFile = new File({
userId,
Dataset,
});
let user;
try {
user = await User.findById(userId);
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again 1',
500
);
return next(error);
}
if (!user) {
const error = new HttpError('Could not find user for provided id', 404);
return next(error);
}
try {
const sess = await mongoose.startSession();
sess.startTransaction();
await createdFile.save({ session: sess });
user.Dataset.push(createdFile);
await user.save({ session: sess });
await sess.commitTransaction();
} catch (err) {
const error = new HttpError(
'Creating place failed, please try again.2',
500
);
return next(error);
}
res.status(201).json({ files: createdFile });
};
The error message that I got
Error: User validation failed: _id: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at ValidationError.inspect (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\error\validation.js:48:26)
at internal/per_context/primordials.js:23:32
at formatValue (internal/util/inspect.js:783:19)
at inspect (internal/util/inspect.js:337:10)
at formatWithOptionsInternal (internal/util/inspect.js:2016:40)
at formatWithOptions (internal/util/inspect.js:1898:10)
at console.value (internal/console/constructor.js:323:14)
at console.log (internal/console/constructor.js:358:61)
at createFile (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\controllers\files-controller.js:102:13)
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
errors: {
_id: ValidatorError: Error, expected `_id` to be unique. Value: `62c661c629d1cb99768efd05`
at validate (C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1321:13)
at C:\Users\acit\Desktop\FYP Code\FYP Code\backend2\node_modules\mongoose\lib\schematype.js:1297:24
at processTicksAndRejections (internal/process/task_queues.js:93:5) {
properties: [Object],
kind: 'unique',
path: '_id',
value: new ObjectId("62c661c629d1cb99768efd05"),
reason: undefined,
[Symbol(mongoose:validatorError)]: true
}
},
_message: 'User validation failed'
}

It already settle, I reroll the mongoose-unique-validator to 2.0.3 version
I use this command
npm install mongoose-unique-validator#2.0.3 --legacy-peer-deps
hope that someone with same issues as mine find my post and can help them to solve the same issues

Related

Property 'body' does not exist on type 'Observable<Object>'. Angular.js Discord OAuth2

Im making a Discord Bot Dashboard and implementing Discord OAuth2. I'm following the guide here: https://discordjs.guide/oauth2/#a-quick-example and the code is essentially the same.
async getJSONResponse(body) {
let fullBody = '';
for await(const data of body) {
fullBody += data.toString();
}
return JSON.parse(fullBody)
}
async getAccessToken(code) {
if (code) {
try {
let body = new URLSearchParams();
body.append('client_id', environment.discord.clientId)
body.append('client_secret', environment.discord.clientSecret)
body.append('code', code)
body.append('grant_type', 'authorization_code')
body.append('redirect_uri', environment.discord.redirect)
body.append('scope', 'identify')
let options = {
headers: new HttpHeaders().set('Content-Type', 'application/x-www-form-urlencoded')
};
const tokenResponseData = await this.http.post('https://discord.com/api/oauth2/token', body.toString(), options)
const oauthData = await this.getJSONResponse(tokenResponseData.body)
console.log(oauthData)
} catch(err) {
console.error('an error')
console.error(err)
}
}
}
However, I get this error: Property 'body' does not exist on type 'Observable<Object>'.
As you can see, the guide above clearly shows that body does in fact exist on the object.
I'm out of ideas, any help is appreciated.
Thanks

Im trying to make a giveaway command based in a tutorial i saw and it says TypeError: Cannot read property 'start' of undefined

As i said in the title i am getting this error, and I don't know how to fix it, but tutorials use the same thing and don't get this error. Pls help me i dont know what to do.
error:
"Cannot read property 'start' of undefined"
const ms = require('ms')
const { MessageEmbed } = require('discord.js')
module.exports = {
name : 'giveaway',
execute : async(message, args ,client) => {
if(!message.member.hasPermission('MANAGE_MESSAGES')) return message.channel.send('You dont have manage messages permission.')
const channel = message.mentions.channels.first()
if(!channel) return message.channel.send('Please specify a channel')
const duration = args[1]
if(!duration) return message.channel.send('please enter a valid duration')
const winners = args[2]
if(!winners) return message.channel.send('Please specify an amount of winners')
const prize = args.slice(3).join(" ")
if(!prize) return message.channel.send('Please sepcify a prize to win')
client.giveaways.start(channel, {
time : ms(duration),
prize : prize,
winnerCount: winners,
hostedBy: message.author,
messages: {
giveaway: "Giveaway \#everyone",
giveawayEnd: "Giveaway Ended \#everyone",
timeRemaining: "Time Remaining **{duration}**",
inviteToParticipate: "React with 🎉 to join the giveaway",
winMessage: "Congrats {winners}, you have won the giveaway",
embedFooter: "Giveaway Time!",
noWinner: "Could not determine a winner",
hostedBy: 'Hosted by {user}',
winners: "winners",
endedAt: 'Ends at',
units: {
seconds: "seconds",
minutes: "minutes",
hours: 'hours',
days: 'days',
pluralS: false
}
},
})
message.channel.send(`Giveaway is starting in ${channel}`)
}
}
error line code: client.giveaways.start(channel, {
index.js:
client.giveaways = new GiveawaysManager(client, {
storage : './giveaways.json',
updateCountdownEvery : 5000,
embedColor: '#D03600',
reaction: '🎉'
})
giveaways.json: []
Execute:
try{
command.execute(message,args, cmd, client, Discord);
} catch (err){
message.reply("There was an error trying to execute this command!");
console.log(err);
}
}
In your command.execute() call, you are passing in client as the fourth parameter. But in your command file, where you export the giveaway command, client is the third parameter.
module.exports = {
name : 'giveaway',
// Add cmd parameter here, so client is passed in correctly as the fourth parameter
execute : async(message, args, cmd, client) => { ... }
}

How to keep a count of number of requests when using mock service worker to test a React App?

In my app, the user enters their date of birth, a request is sent, and if it matches with the DOB in the database, they are sent to the next page. If it does not match, they are presented with the number of attempts they have left until their link is no longer valid. They have 3 attempts.
My question is, how would I mock this functionality using mock service worker? I would need to keep a count of the number of times this request has been attempted and failed.
Here is the code snippet of the handler, as you can see I have hardcoded the "1" after "Auth attempts" for now.
rest.post(
'https://myapiaddress/auth',
(req, res, ctx) => {
const enteredDateOfBirth = req.body.data.date_of_birth
let returnResult
if (enteredDateOfBirth === '1988-10-01') {
returnResult = res(
ctx.status(200),
ctx.json({
data: {
basic: 'fdafhaioubeaufbaubsaidbnf873hf8faoi'
}
})
)
} else {
returnResult = res(
ctx.status(400),
ctx.json({
errors: [
{ code: 89, message: 'Wrong date of birth. Auth attempts: 1' }
]
})
)
}
return returnResult
}
)
]
My jest test in which I confirm the incorrect date 3 times:
// 1st attempt
userEvent.click(confirmBtn)
const warningAttemptsNum1 = await screen.findByText('1/3 attempts')
const dateEntered = screen.getByText('(12/10/2010)')
expect(warningAttemptsNum1).toBeInTheDocument()
expect(dateEntered).toBeInTheDocument()
// 2nd attempt
userEvent.click(confirmBtn)
const warningAttemptsNum2 = await screen.findByText('2/3 attempts')
expect(warningAttemptsNum2).toBeInTheDocument()
userEvent.click(confirmBtn)
// Entering 3 times shows "link no longer valid" screen
userEvent.click(confirmBtn)
const linkNoLongerValidText = await screen.findByText(
'This link is no longer valid'
)
expect(linkNoLongerValidText).toBeInTheDocument()
Your general idea is correct: you can keep a track of the count of requests made by incrementing a number in the response resolver.
Here's how I'd recommend doing it:
function withTimes(handler) {
let attempts = 0
return (req, res, ctx) => {
attempts++
handler(req, res, ctx, attempts)
}
}
rest.post('/endpoint', withTimes((req, res, ctx, attempts) => {
const MAX_ATTEMPTS = 3
const dob = req.body.data.date_of_birth
if (dob === '1988-10-01') {
return res(ctx.json({ data: { basic: 'abc-123' }}))
}
return res(
ctx.status(400),
ctx.json({
errors: [
{
code: 89,
message: `Wrong date of birth. Attempts left: ${MAX_ATTEMPTS - attempts}`
}
]
})
)
}))
I also see that the response body structure you use is very similar to such of GraphQL. Note that you should use the GraphQL API to handle GraphQL operations.

findOneAndUpdate causing duplication problem

I am having a problem in findOneAndUpdate in mongoose.
The case is that i am updating a document by finding it.
The query is as follows:
UserModel.findOneAndUpdate({
individualId: 'some id'
}, {
$push: {
supporterOf: 'some string'
}
})
The 'supporterOf' is the ref of UserModel and its type is 'ObjectId'.
The issue i am facing here is that, 'some string' is being pushed twice under 'supporterOf' in the document.
Can anyone tell me that how to push an array element inside the document?
I was having same problem, solution is.
I was keeping await like below.
**await** schema.findOneAndUpdate(queryParms, {
"$push": {
"array1": arrayDetails,
"array2": array2Details
}
}, {
"upsert": true,
"new": true
},
function (error, updateResponse) {
if (error) {
throw new Error (error);
} else {
// do something with updateResponse;
}
});
simply removing await helped me resolving this problem.
Need to find the root cause.
any pointer for references are welcome.
I have recently encountered the same problem. However, I managed to overcome this issue by some other logics (details given below) but couldn't understand the reason behind that why findOneAndUpdate inserting duplicate entries in mongodb.
You can overcome this problem by following logic.
Use findOne or findById instead of findOneAndUpdate to search the document in your collection and then manually update your document and run save().
You can have better idea with this code snippet
return new Promise(function (resolve, reject) {
Model.findOne({
someCondition...
}, function (err, item) {
if (err) {
reject(err);
} else {
item.someArray.push({
someKeyValue...
});
item.save().then((result) => {
resolve(result)
}).catch((err) => {
reject(err)
});
}
}).catch((err) => {
reject(err)
});
});
This will not insert duplicate item. However, if you come to know the reasoning behind duplication, must do update this thread.
The issue seems to stem from combining an await and a callback. I had the same issue until I realised I was using an (err, resp) callback and a .catch(...).
models[auxType].findOneAndUpdate(
filter,
updateObject,
options,
(err, resp)=>{
if (err) {
console.log("Update failed:",err)
res.json(err)
} else if (resp) {
console.log("Update succeeded:",resp)
res.json(resp)
} else {
console.log("No error or response returned by server")
}
})
.catch((e)=>{console.log("Error saving Aux Edit:",e)}); // << THE PROBLEM WAS HERE!!
The problem resolved as soon as I removed the .catch(...) line.
From the mongoose documentation:
"Mongoose queries are not promises. They have a .then() function for co and async/await as a convenience. However, unlike promises, calling a query's .then() can execute the query multiple times."
(https://mongoosejs.com/docs/queries.html#queries-are-not-promises)
Use $addToSet instead of $push, it should solve the problem. I believe there is an issue with the data structure used in the creation of a mongoose 'Model'. As we know push is an array (which allows duplication) operation while addToSet may be a Set operation (Sets do not allow duplication).
The problem with the accepted answer is that it only solves the problem by wrapping it in an unnecessary additional promise, when the findOneAndUpdate() method already returns a promise. Additionally, it uses both promises AND callbacks, which is something you should almost never do.
Instead, I would take the following approach:
I generally like to keep my update query logic separate from other concerns for both readability and re-usability. so I would make a wrapper function kind of like:
const update = (id, updateObj) => {
const options = {
new: true,
upsert: true
}
return model.findOneAndUpdate({_id: id}, {...updateObj}, options).exec()
}
This function could then be reused throughout my application, saving me from having to rewrite repetitive options setup or exec calls.
Then I would have some other function that is responsible for calling my query, passing values to it, and handling what comes back from it.
Something kind of like:
const makePush = async () => {
try {
const result = await update('someObjectId', {$push: {someField: value}});
// do whatever you want to do with the updated document
catch (e) {
handleError(e)
}
}
No need to create unnecessary promises, no callback hell, no duplicate requests, and stronger adherence to single responsibility principles.
I was having the same problem. My code was:
const doc = await model.findOneAndUpdate(
{filter}, {update},
{new: true}, (err, item) => if(err) console.log(err) }
)
res.locals.doc = doc
next();
The thing is, for some reason this callback after the "new" option was creating a double entry. I removed the callback and it worked.
I had the same problem.
I found a solution for me:
I used a callback and a promise (so using keyword "await") simultaneously.
Using a callback and a promise simultaneously will result in the query being executed twice. You should be using one or the other, but not both.
options = {
upsert: true // creates the object if it doesn't exist. defaults to false.
};
await Company.findByIdAndUpdate(company._id,
{ $push: { employees: savedEmployees } },
options,
(err) => {
if (err) {
debug(err);
}
}
).exec();
to
options = {
upsert: true // creates the object if it doesn't exist. defaults to false.
};
await Company.findByIdAndUpdate(company._id,
{ $push: { employees: savedEmployees } },
options
).exec();
UserModel.findOneAndUpdate(
{ _id: id },
{ object }
)
Even if you use _id as a parameter don't forget to make the filter explicit by id
In my case, changing the async callback solved the problem.
changing this:
await schema.findOneAndUpdate(
{ queryData },
{ updateData },
{ upsert: true },
(err) => {
if (err) console.log(err);
else await asyncFunction();
}
);
To this:
await schema.findOneAndUpdate(
{ queryData },
{ updateData },
{ upsert: true },
(err) => {
if (err) console.log(err);
}
);
if (success) await asyncFunction();
The $addToSet instead of $push allowed me to prevent duplicate entry in my mongoDb array field of User document like this.
const blockUserServiceFunc = async(req, res) => {
let filter = {
_id : req.body.userId
}
let update = { $addToSet: { blockedUserIds: req.body.blockUserId } };
await User.findOneAndUpdate(filter, update, (err, user) => {
if (err) {
res.json({
status: 501,
success: false,
message: messages.FAILURE.SWW
});
} else {
res.json({
status: 200,
success: true,
message: messages.SUCCESS.USER.BLOCKED,
data: {
'id': user._id,
'firstName': user.firstName,
'lastName': user.lastName,
'email': user.email,
'isActive': user.isActive,
'isDeleted': user.isDeleted,
'deletedAt': user.deletedAt,
'mobileNo': user.mobileNo,
'userName': user.userName,
'dob': user.dob,
'role': user.role,
'reasonForDeleting': user.reasonForDeleting,
'blockedUserIds': user.blockedUserIds,
'accountType': user.accountType
}
});
}
}
).catch(err => {
res.json({
status: 500,
success: false,
message: err
});
});
}

How to write to google finance API?

I know how to read from the google finance api, it is pretty simple.
But when I try to write I get the following error:
Error: Request had insufficient authentication scopes
This is my code:
const fs = require('fs');
const readline = require('readline');
const {google} = require('googleapis');
// If modifying these scopes, delete token.json.
const TOKEN_PATH = 'token.json';
// Load client secrets from a local file.
fs.readFile('./GoogleFinanceApi/credentials.json', (err, content) => {
if (err) return console.log('Error loading client secret file:', err);
// Authorize a client with credentials, then call the Google Sheets API.
authorize(JSON.parse(content), appendData);
});
Here ^ in the append data is where I am calling the function, it works when i do the listMajors but not when I do the appendData...
function authorize(credentials, callback) {
const {client_secret, client_id, redirect_uris} = credentials.installed;
const oAuth2Client = new google.auth.OAuth2(
client_id, client_secret, redirect_uris[0]);
// Check if we have previously stored a token.
fs.readFile(TOKEN_PATH, (err, token) => {
if (err) return getNewToken(oAuth2Client, callback);
oAuth2Client.setCredentials(JSON.parse(token));
callback(oAuth2Client);
});
}
function listMajors(auth) {
const sheets = google.sheets({version: 'v4', auth});
sheets.spreadsheets.values.get({
spreadsheetId: '1ckHZsL2fnWVATmXljlewm-6qBo62B0qmu0w_2QdSpGA',
range: 'Sheet1!A2:E',
}, (err, res) => {
if (err) return console.log('The API returned an error: ' + err);
const rows = res.data.values;
if (rows.length) {
console.log('Name, Major:');
// Print columns A and E, which correspond to indices 0 and 4.
rows.map((row) => {
console.log(`${row[0]}, ${row[4]}`);
});
} else {
console.log('No data found.');
}
});
}
function appendData(auth) {
var sheets = google.sheets('v4');
sheets.spreadsheets.values.append({
auth: auth,
spreadsheetId: '1ckHZsL2fnWVATmXljlewm-6qBo62B0qmu0w_2QdSpGA',
range: 'Sheet1!A2:B', //Change Sheet1 if your worksheet's name is something else
valueInputOption: "USER_ENTERED",
resource: {
values: [ ["Void", "Canvas", "Website"], ["Paul", "Shan", "Human"] ]
}
}, (err, response) => {
if (err) {
console.log('The API returned an error: ' + err);
return;
} else {
console.log("Appended");
}
});
}
What am I doing wrong? I have read some posts and they say they didn't add the resource so I tried to fix that but still nothing works...
Probably the issue is in google.sheets in appendData. Perhaps you need to pass auth to google.sheets before you access sheets as how you are doing in listMajors but you are passing auth to the sheets instead of google.sheets. This might be an issue
Can you try below updated code
function appendData(auth) {
const sheets = google.sheets({version: 'v4', auth})
sheets.spreadsheets.values.append({
spreadsheetId: '1ckHZsL2fnWVATmXljlewm-6qBo62B0qmu0w_2QdSpGA',
range: 'Sheet1!A2:B', //Change Sheet1 if your worksheet's name is something else
valueInputOption: "USER_ENTERED",
resource: {
values: [ ["Void", "Canvas", "Website"], ["Paul", "Shan", "Human"] ]
}
}, (err, response) => {
if (err) {
console.log('The API returned an error: ' + err);
return;
} else {
console.log("Appended");
}
});
}

Resources