$regex requires regular expression error mongodb stitch - javascript

I get this error when I try to query to Mongodb Stitch:
Error: $regex requires regular expression
at client.js:557
Here is my code:
const searchByName = async (data) => {
let db = await MongoConnect(),
collection_users = db.collection('users'),
users
console.log(data.name)
let regxName = new RegExp(data.name)
console.log(regxName)
try {
let users = await collection_users.find({ name: { $regex: regxName,
$options: 'i' } }).execute()
console.log(users)
} catch (error) {
return error
}

Thanks for the help, this method works. (All client side)
import { BSON } from 'mongodb-stitch'
let bsonRegex = new BSON.BSONRegExp('pattern', 'i')
let users = await collection_users.find({ name: bsonRegex }).execute()
Returns results from pattern

In MongoDB Stitch Functions you have to use BSON.BSONRegExp global function that will convert it to correct format for Stitch.
Here is an example :
exports = function(keyword) {
var mongodb = context.services.get("mongodb-atlas");
var coll = mongodb.db("DBNAME").collection("users");
return coll.find({
name: BSON.BSONRegExp(keyword, "i")
}).toArray();
};
and call it on client like :
stitchClientPromise.then(stitchClient =>
stitchClient.executeFunction('FUNC_NAME', 'jhon')
).then(users => console.log('success: ', users))
.catch(e => console.log('error: ', e));

Related

Getting total Number of User Items in Firebase Realtime database in javascript

I have been trying to get amount of users that have same "referralId" in my firebase Realtime database,
users {
AY35bkc5cbkufik8gfe3vjbmgr {
email: james #gmail.com
verify: none
referralid: AY35ja35
}
B16fty9jDchfNgdx7Fxnjc5nxf5v {
email: mobilewisdom #gmail.com
verify: none
referralid: AY35ja35
}
}
How can I use JavaScript to count the amount of account with referralid:AY35ja35
I tried:
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
query.get().then((results) => {
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
});
But am getting this error in my console:
Uncaught TypeError: query.get is not a function
In v8/namespaced syntax that'd be:
const ref = firebase.database().ref('users');
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
const results = await query.get();
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
Or if you're in an environment where await doesn't work:
const ref = firebase.database().ref('users');
const query = ref.orderByChild('referralid').equalTo('AY35ja35');
query.get().then((results) => {
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
});
In v9/modular syntax the equivalent would be:
const ref = ref(getDatabase(), 'users');
const query = query(ref, orderByChild('referralid'), equalTo('AY35ja35'));
const results = await get(query);
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
Or if you're in an environment where await doesn't work:
const ref = ref(getDatabase(), 'users');
const query = query(ref, orderByChild('referralid'), equalTo('AY35ja35'));
get(query).then((results) => {
console.log(Object.keys(results.val()).length);
results.forEach((snapshot) => {
console.log(snapshot.key, snapshot.val());
});
});
Firstly you will have to run a query to get the data from firebase using either firebase package, axios or fetch
Your data is fetched in form of Object containing different objects. You can either user for .. in .. loop to iterate through the object.
var count = 0
for (const user in users) {
if (user.referralid==="AY35ja35") {
count++
}
}
Or use Object.values(object) function to get array of users. Now you can use a JavaScript array function such as map or filter.
by using map. you can do it like this:
var count=0
user.map(user=>{if(user.referralid==="AY35ja35"){count++})
or by using filter
const matchedUsers = user.filter(user=>(user.referralid==="AY35ja35"))
const count = matchedUsers.length
Hope this helps :)

Nodejs mssql bulk insert RequestError: Invalid object name 'table_name'

I am trying to use nodejs mssql package for bulk insert into existing table.It give error as Invalid Object Name 'my_test' even my table is already there and i have tried 'db.schema.tablename' or 'schema.tablename' both. Please help me on that and Thanks in advance. My code part is like below - :
async function getPool(name) {
if (!Object.prototype.hasOwnProperty.call(pools, name)) {
const pool = process.env.NODE_ENV.trim() === 'local' ? new sql.ConnectionPool(configLocal) : new sql.ConnectionPool(config);
const close = pool.close.bind(pool);
pool.close = (...args) => {
delete pools[name]
return close(...args)
}
await pool.connect();
pools[name] = pool;
}
return pools[name];
}
const pool = await getPool('default');
const table = new sql.Table('my_test'); // or temporary table, e.g. #temptable
table.create = false;
table.columns.add('id', sql.Int, { nullable: false,primary:true,identity:true});
table.columns.add('name', sql.VarChar(50), { nullable: false });
table.rows.add(10, 'test');
table.rows.add(11, 'test 2');
const request = new sql.Request(pool);
request.bulk(table, (err, result) => {
console.log("Result ", result, err);//return result;
}); ```

CypressIO Returning string value from cy.task() using cy.wrap() gives error "cy is not defined"

In cypress /plugins/index.js I have code to query oracleDB
module.exports = (on, config) => {
on('task', {
'registration': async (email) => {
const oracledb = require('oracledb');
oracledb.initOracleClient({libDir: './oracleClient'});
let result;
let connection;
connection = await oracledb.getConnection( {
user : process.env.ORACLEDB_USER,
password : process.env.ORACLEDB_PASSWORD,
connectString : "localhost/STORE"
});
result = await connection.execute(
"select ..."
);
console.log(result.rows)
var extractedUrlText = JSON.stringify((await result).rows).extract('/VerifiedRegistrationFormView','\"');
console.log('Extracted URL: \r\n' + extractedUrlText);
return cy.wrap(extractedUrlText);
}
});
}
This returns the correct extracted URL in Node terminal.
But then in my cypress test, when I try to use that extractedUrlText string value i'm getting error cy is not defined:
it('Register a new user', () => {
cy.task('registration', emailAddress, { timeout: 10000 }).then(value => cy.log(value)) // cy is not defined
})
I use a similiar approach to use a returned value from support/commands.js Cypress.Commands.add() and it works there, but not from cy.task() using cy.wrap()
My working solution:
/plugins/index.js extended from above code:
var extractedUrlText = JSON.stringify((await result).rows).extract('/VerifiedRegistrationFormView','\"');
console.log('Extracted NODE URL: \r\n' + extractedUrlText);
return extractedUrlText
}
In spec file:
let extractedUrl;
cy.task('registration', emailAddress).then(value => {
extractedUrl = value;
cy.log('Extracted CY URL: ' + extractedUrl)
})
Result:

Why am I not able to catch a Discord.js error in a command handler?

So I'm new to Javascript and trying to making a discord bot. Here is a very small portion that illustrates my problem:
module.exports = {
name: "match",
category: "LOL",
description: "Give Summoner's Data to User",
run: async (client, message, args) => {
var username = `${args}`
var regionID= "na1"
pyke.summoner.getBySummonerName(username, regionID).then(data => {
return pyke.spectator.getCurrentGameInfoBySummoner(`${data.id}`, "na1").then(result => {
try {
console.log(result)
} catch (err) {
console.error(`${args} isn't in game!`)
}
})
})
}
}
I was expected to see if an error cause, it will send a code to a console. However, I get a UnhandledPromiseRejectionWarning. My question is why can't I catch an error and send a code to the console?
So This is what I try for the command
const property1 = result.participants.summonerName
const BResult = property1
let FResult = JSON.stringify(BResult)
message.channel.send(FResult)
and when I try, I got an error says that this person isn't in-game. I know it's false because they are in-game.
So I went further and try to do this instead.
const property1 = result.participants[summonerName]
const BResult = property1
let FResult = JSON.stringify(BResult)
message.channel.send(FResult)
I still get the same result from the last one. I also try to do const property1 = result.summonerName, but it didn't work as well.
Try instead to wrapping the pyke.spectator.getCurrentGameInfoBySummone in a try/catch. This example uses try/catch with the await keyword:
module.exports = {
name: "match",
category: "LOL",
description: "Give Summoner's Data to User",
run: async (client, message, args) => {
const username = `${args}`;
const regionID = "na1";
return pyke.summoner.getBySummonerName(username, regionID).then((data) => {
try {
const result = await pyke.spectator.getCurrentGameInfoBySummoner(`${data.id}`, "na1");
console.log(result);
} catch (err) {
console.error(`${args} isn't in game!`);
}
});
},
};
Otherwise you can try just using a Promise catch for the error:
module.exports = {
name: "match",
category: "LOL",
description: "Give Summoner's Data to User",
run: async (client, message, args) => {
const username = `${args}`;
const regionID = "na1";
return pyke.summoner.getBySummonerName(username, regionID).then((data) => {
return pyke.spectator.getCurrentGameInfoBySummoner(`${data.id}`, "na1")
.then(result => {
console.log(result);
})
.catch(err => {
console.error(`${args} isn't in game!`)
});
});
},
};
You can use JSON.stringify to stringify an object and you can use a variety of different methods such as destructuring to extract specific properties you only want to return in combination with creating/returning a new object:
// extract specific properties from `result`
// This is use ES6 destructuring, but you can use dot notation instead or whatever you prefer
const { property1, property2, property 3 } = result;
// return the stringified object only with the properties you need
const payload = { property1, property2 ,property };
return JSON.stringify(payload)

Hyperledger query never return results

I`m trying to query my business network using buildQuery but it always returns an empty array.
My code is as follows.
This is the connection.js file:
module.exports = {
BusinessNetworkConnection : require('composer-client').BusinessNetworkConnection,
cardName : '',
connection: {},
connect : function() {
var cardType = { type: 'composer-wallet-filesystem' }
this.connection = new this.BusinessNetworkConnection(cardType);
return this.connection.connect(this.cardName);
},
disconnect : function(callback) {
this.connection.disconnect();
}
};
This is my query.js file which being invoked to get results:
const connection = require('./connection');
const getContacts = async (cardName,companyID) => {
connection.cardName = cardName;
try {
await connection.connect();
main();
} catch (error) {
main(error);
}
async function main(error) {
if (error) { return new Error("Ops Error: ",error) };
const statement = 'SELECT org.finance.einvoice.participant.Company WHERE (participantId == _$companyID)'
const query = await connection.connection.buildQuery(statement);
const company = await connection.connection.query(query, { companyID }).catch(err => {return new Error(err)});
await connection.connection.disconnect().catch(err => new Error(err));
console.log(company);
return company;
};
};
module.exports = {
getContacts
};
The expected behavior from getContacts() is to return an asset from business network but it actually returns an empty array.
Current versions: composer-cli 0.20 , composer-playground 0.20 , composer-client 0.20 , composer-common 0.20 and fabric-dev-server 1.2 .
i found the solution for this issue.
i was using card which was not allowed to perform queries. However, when i used the admin card it returned with results.
other way is to allow participants to issue queries in permission.acl file.

Categories

Resources