How to find "By Name" in mongoose - javascript

I am trying to get database values using a specific name. I want to get all the books an author written.
This is my code to get the first name of the author and search for all the books he's written in BookDB using Like operator as in mysql
//get books by author name
router.route('/authorName').get((req, res) => {
let authorName = req.params.authorName; //how can i pass this value to below regex command
BookDB.find({"firstName": /authorName/}, (err, books) => {
if(err) throw err;
res.status(200).send(books);
});
});
Problem: How can I pass authorName to the {"firstName": /authorName/}.
The way I have written, it is not set the authorName properly.

I am not sure in the mongoose part, but you can also create regular expressions as:
new RegExp(exp: string, flags: string)
Note if you use this format, the start and end slash has no special meaning, they would mean the string starts with a slash

I did some research and found $regex.
//get books by author name
router.route('/authorName').get((req, res) => {
let authorName = req.params.authorName;
BookDB.find({firstName: {$regex: `${authorName}`}}, (err, books) => {
if(err) throw err;
res.status(200).send(books);
});
});
This will find all the results that containing this particular string authorName in BookDB database

Related

node js sql output

I am trying to come up with the node.js code to get the output of this query:
const viewAllEmployees = () => {
let sql = 'SELECT e.id, e.first_name, e.Last_name, r.title, d.name as "Department", salary, CONCAT (m.first_name," ", m.last_name) AS "Manager"
FROM employee e ' + connection.escape('INNER JOIN employee m
ON e.manager_id = m.id
LEFT JOIN role r
ON e.role_id = r.id
LEFT JOIN department d
on r.department_id = d.id');
connection.query(sql, (err, res) => {
if (err) throw err;
console.table(res);
// console.log(res);
//connection.end();
});
The problem is that when I use it without the connection.escape(), I get the output, but with single quotes like this:
How can I (1) get rid of the (index) column, and (2) get rid of the single quotes?
Getting rid of the single quotes is really the priority.
Thanks!
Index column and quotes are added by console.table function itself.
You can check it running console.table with any static data like here:
https://developer.mozilla.org/en-US/docs/Web/API/Console/table#collections_of_primitive_types
To print it in a way you want it, implement printing function on your own.

delete user from json table in js

So I'm a beginner to js and I have a table of users in a json file and I'm making an account delete feature. I have a find set up to find the user and it works fine but I can't figure out how to make it delete the user from the file, any help would be appreciated!
Json:
{
"users": [
{
"name": "ImBattleDash",
"Id": "780748c5d4504446bbba3114ce48f6e9",
"discordId": "471621420162744342",
"dateAdded": 1548295371
}
]
}
JS:
function findJson() {
fs.readFile('./linkedusers.json', 'utf-8', function (err, data) {
if (err) message.channel.send('Invalid Code.')
var arrayOfObjects = JSON.parse(data)
let findEntry = arrayOfObjects.users.find(entry => entry.discordId == myCode)
let linkEmbed = new Discord.RichEmbed()
.setTitle('Account unlinked!')
.setDescription('Link your account by friending "BattleDash Bot" on Fortnite and then input the code you get messaged by typing "!link <code>"!')
.setColor('#a900ff');
message.channel.send({embed: linkEmbed});
})
}
EDIT: Not sure if it's an array or a table I don't know a lot about json
You need to use:
Array#find to find a given user by some given criteria.
Array#indexOf to get the index of the found user in users
Array#splice to drop one element starting from the index given by Array#indexOf:
const input = {
"users": [
{
"name": "ImBattleDash",
"Id": "780748c5d4504446bbba3114ce48f6e9",
"discordId": "471621420162744342",
"dateAdded": 1548295371
}
]
}
const removeUser = (criteria, users) =>
users.splice (users.indexOf (users.find (criteria)), 1)
removeUser (
({ Id, discordId }) =>
Id == '780748c5d4504446bbba3114ce48f6e9'
&& discordId == '471621420162744342',
input.users
)
// Output: 0 <-- User has been removed!
console.log(input.users.length)
About persisting the change, it's just about calling JSON.stringify (input) and then just write the contents to the desired output file. See this other Q&A: Writing files in Node.js
With great help from Cat and Matias I came up with this code that works!
function findJson() {
fs.readFile('./linkedusers.json', 'utf-8', function (err, data) {
if (err) message.channel.send('Invalid Code.')
var arrayOfObjects = JSON.parse(data)
let findEntry = arrayOfObjects.users.find(entry => entry.discordId == myCode)
const input = arrayOfObjects;
const removeUser = (criteria, users) =>
users.splice (users.indexOf (users.find (criteria)), 1)
removeUser (
({ Id, discordId }) =>
Id == findEntry.Id
&& discordId == findEntry.discordId,
input.users
)
console.log('unlinked')
fs.writeFile('./linkedusers.json', JSON.stringify(arrayOfObjects, null, 4), 'utf-8', function(err) {
if (err) throw err
console.log('Done!')
})
let linkEmbed = new Discord.RichEmbed()
.setTitle('Account unlinked!')
.setDescription('Link your account by friending "BattleDash Bot" on Fortnite and then input the code you get messaged by typing "!link <code>"!')
.setColor('#a900ff');
message.channel.send({embed: linkEmbed});
})
}
Here's a quick tutorial for you:
"Users" would be either an array (using []) or a javascript object (using {}), your choice. There won't be any actual tables unless you use a database instead of a JSON file (although if your JSON expression is as simple as your example, you could almost think of it as a table.) -- And actually, a third option would be to use the javascript Map type, which is like a beefed-up object, but I won't address that here.
While using an array would make it a bit easier to retrieve a list of data for all users (because arrays are simpler to iterate through), using an object would make it considerably easier to retrieve data for a single user (since you can directly specify the user you want by its key instead of needing to loop through the whole array until you find the one you want.) I'll show you an example that uses an object.
The individual user in your sample code is an example of a javascript object. JSON lets you convert an object to a string (for storage, I/O, and human readability) and back to an object (so javascript can understand it). You use the JSON.stringify() and JSON.parse() methods, respectively for these conversions. The string has to be JSON-formatted or this won't work, and your example is almost in JSON format.
To comply with JSON formatting, you could structure a Users object as follows. (Of course we're looking at the stringified version because mere humans can't easily read an "actual" javascript object):
"Users": { // Each individual user is a property of your users object
"780748c5d4504446bbba3114ce48f6e9": // The Id is the key in the "key/value pair"
{ // The individual user object itself is the value in the key/value pair
// Id is duplicated inside user for convenience (not necessarily the best way to do it)
"id": "780748c5d4504446bbba3114ce48f6e9",
"name": "ImBattleDash", // Each property of the user is also a key/value pair
"discordId": "471621420162744342", //Commas separate the properties of an object
"dateAdded": "1548295371" // All property values need double quotes for JSON compatibility
}, // Commas separate the properties (ie the individual users) of the users object
"446bbba3114ce48f6e9780748c5d4504": // This string is the second user's key
{ // This object is the second user's value
"id": "446bbba3114ce48f6e9780748c5d4504",
"name": "Wigwam",
"discordId": "162744342471621420",
"dateAdded": "1548295999"
}
}
Once you retrieve the string from storage, you convert it to an object and delete a user as follows. (This is broken down into more steps than necessary for clarity.):
let usersObject = JSON.parse(stringRetrievedFromFile);
let userId = "780748c5d4504446bbba3114ce48f6e9";
let userToModifyOrDelete = usersObject[userId];
delete userToModifyOrDelete;
To change the user's discordId instead, you would do:
let discordId = userToModifyOrDelete.discordId; // Not necessary, just shows how to retrieve value
let newDiscordId = "whateverId";
userToModifyOrDelete.discordId = newDiscordId;
And you'd convert the object back into a string to store in your file with:
JSON.stringify(usersObject);
Hopefully that's almost all you need to know about JSON!

Nodejs Subselect in sql select

Ola!
I'm doing a node.js application. I have this table structure in my MySql DB:
My task is to get the table_4 names and the related table_7 names. I know the Table_1 username and password. Is it possible to create one query - using subselect - not calling all the time callback with a new select after getting values? - like below -
con.connect(function(err) {
if (err)
{throw err }
con.query("SELECT id FROM Table_1 WHERE username = xyz AND password = aaa",
function (err, result) {
if (err) {throw err};
con.query("SELECT table_3_id FROM table2 WHERE Table_1_id = "+(result)+")",
function(/*bla-bla*/){
};
});
}
);
Thanks!
Here it is how you can achieve that with one query :
SELECT Table_4.*
FROM Table_1 , Table_2 , Table_3 , Table_4
WHERE Table_1.username and Table_1.password and
Table_2.Table_1_id = Table_1.id and
Table_2.Table_3_id = Table_3.id and
Table_3.Table_4_id = Table_4.id
I couldn't found proper relations for Table_7 names. But I think you will get idea how to do it further from this.
I just talked to my lead dev, hwho gave me a correct solution - similar to #Vivek Doshi answer - :
SELECT Table_4.names, Table_7.names
FROM Table_1 , Table_2 , Table_3 , Table_4, Table_5, Table_6, Table_7
WHERE Table_1.username and Table_1.password and
Table_2.Table_1_id = Table_1.id and
Table_2.Table_3_id = Table_3.id and
Table_3.Table_4_id = table_4.id and
Table_3.table_5_id = table_5.id and
table_6.table_5_id = Table_5.id and
table_6.table_7_id = table_7.id;

mongoose delete duplicate docs but not the first one

I used findOneAndRemove to delete duplicate because I knew there was not more than 2 docs with the same "name" value. That would delete the first instance of a doc that has the same "name" value. Now I don't want to delete the first instance. Instead, I want to delete all the other ones. so if there are 3 docs that have the {name: "/face.com"} it should only leave the first one that was added and delete the other 2.
Comps.find({}).lean()
.then(function(comps){
findDuplicates.getArrayOfNames(comps);
var dups = findDuplicates.checkForDuplicates();
//dups is an array of names. It contains a list like ["/face.com", "/example.com"]. those are the ones that are duplicates.
console.log("DUPS::", dups)
dups.forEach(function(e){
var query = {name : e}
Comps.findOneAndRemove(query, function(err, removed){
if(err) console.log(err);
console.log("removed: ", removed)
})
})
console.log("length: ", comps.length);
})
.catch(function(err){
console.log("ERR",err)
})

node-mssql Transaction insert - Returning the inserted id..?

I'm using node-mssql 3.2.0 and I need to INSERT INTO a table and return the id of the inserted record.
I can successfully use sql.Transaction() to insert data, but the only parameters given to callbacks (request.query() and transaction.commit()) are:
const request = new sql.Request();
request.query('...', (err, recordset, affected) => {});
const transaction = new sql.Transaction();
transaction.commit((err) => {});
So recordset is undefined for INSERT, UPDATE and DELETE statements, and affected is the number of rows affected, in my case 1.
Does anyone know a good way to obtain an inserted records id (just a primary key id) after a transaction.commit() using node-mssql..?
Instead of just doing an INSERT INTO... statement, you can add a SELECT... statement as well:
INSERT INTO table (...) VALUES (...); SELECT SCOPE_IDENTITY() AS id;
The SCOPE_IDENTITY() function returns the inserted identity column, which means recordset now contains the id:
const request = new sql.Request();
request.query('...', (err, recordset, affected) => {});
I don't think request.multiple = true; is required, because although this includes multiple statements, only one of them is a SELECT... and so returns.
So the answer was SQL related and is not specific to node-mssql.
I know this question has accepted answer.
I made the following way:
let pool = await sql.connect(config);
let insertItem = await pool.request()
.input('ItemId',sql.NVarChar, 'itemId1234')
.input('ItemDesc',sql.NVarChar, 'nice item')
.query("insert into itemTable (Id, ItemId,ItemDesc) OUTPUT INSERTED.ID
values (NEWID(), #ItemId, #ItemDesc);
var insertedItemId = insertItem.recordset[0].ID
This adds unique identifier to data that is saved to db (if table is created so)
create table itemTable(
Id UNIQUEIDENTIFIER primary key default NEWID(),
ItemId nvarchar(25),
ItemDesc nvarchar(25)
)

Categories

Resources