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

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;
}); ```

Related

My findIndex is not working as should using Node.js and mongo DB as database

Ihave some issues trying to find a index of an expecific product in a mongo database.
const cart = await this.model.findOne({ user: { $eq: user } });
if (cart) {
const itemFound = cart.products.findIndex(
(item) => item._id === new ObjectId(obj._id)
);
I'm sending the id from the frontend as a string and I transform it with the new ObjectId, the issue is it gives me -1, when I console log the item._id and new ObjectId(obj._id). Are the same but I dont know why it gives me -1.
this is the whole fuction I want to do:
async editCart(obj, user) {
try {
const cart = await this.model.findOne({ user: { $eq: user } });
if (cart) {
const itemFound = cart.products.findIndex(
(item) => item._id === new ObjectId(obj._id)
);
if (itemFound !== -1) {
let product = cart.products[itemFound];
product.count += obj.count;
const saved = await cart.save();
return saved;
} else {
cart.products.push(obj);
const saved = await cart.save();
return saved;
}
} else {
const newCart = new this.model({
products: obj,
user: user,
});
const saved = await newCart.save();
return saved;
}
} catch (error) {
logger.error(`Error to edit cart ${error}`);
throw new Error(error);
}
}
If you find another way to do it I will be really greatfull
You can use .toString() when you want to compare to ObjectId values:
const itemFound = cart.products.findIndex(
(item) => item._id.toString() === obj._id.toString()
);

NodeJS: Getting undefined on cart id

I am defining the cart variable with await cartsRepo.create({ items: [] });, but I continue to get undefined on cart.
My guess is that the request never resolves, so it never drops into the if conditional, but not sure.
Part of the error was unhandled promise rejection so I threw it all into a try/catch block, but I am still getting undefined on cart.
const express = require("express");
const cartsRepo = require("../repositories/carts");
const router = express.Router();
// Receive a post request to add an item to a cart
router.post("/cart/products", async (req, res) => {
console.log(req.body.productId);
// Figure out the cart!
try {
let cart;
if (!req.session.cartId) {
// // we dont have a cart, we need to create one,
// // and store the cart id on the req.session.cartId property
cart = await cartsRepo.create({ items: [] });
req.session.cartId = cart.id;
} else {
// // We have a cart! Lets get it from the repository
cart = await cartsRepo.getOne(req.session.cartId);
}
const existingItem = cart.items.find(
(item) => item.id === req.body.productId
);
if (existingItem) {
// increment quantity and save cart
existingItem.quantity++;
} else {
// add new product id to items array
cart.items.push({ id: req.body.productId, quantity: 1 });
}
await cartsRepo.update(cart.id, {
items: cart.items,
});
} catch (error) {
console.log(error);
}
res.send("Product added to cart");
});
// Receive a get request to show all items in cart
// Receive a post request to delete an item from a cart
module.exports = router;
The missing piece probably is that I am not using a database but created this repository.js file that where all my data is being stored inside some json files:
const fs = require("fs");
const crypto = require("crypto");
module.exports = class Repository {
constructor(filename) {
if (!filename) {
throw new Error("Creating a repository requires a filename");
}
this.filename = filename;
try {
fs.accessSync(this.filename);
} catch (error) {
fs.writeFileSync(this.filename, "[]");
}
}
async create(attrs) {
attrs.id = this.randomId();
const records = await this.getAll();
records.push(attrs);
await this.writeAll(records);
}
async getAll() {
return JSON.parse(
await fs.promises.readFile(this.filename, {
encoding: "utf8"
})
);
}
async writeAll(records) {
// write the updated 'records' array back to this.filename
await fs.promises.writeFile(
this.filename,
JSON.stringify(records, null, 2)
);
}
randomId() {
return crypto.randomBytes(4).toString("hex");
}
async getOne(id) {
const records = await this.getAll();
return records.find(record => record.id === id);
}
async delete(id) {
const records = await this.getAll();
const filteredRecords = records.filter(record => record.id !== id);
await this.writeAll(filteredRecords);
}
async update(id, attrs) {
const records = await this.getAll();
const record = records.find(record => record.id === id);
if (!record) {
throw new Error(`Record with id ${id} not found`);
}
// record === { email: "test#test.com" }
// attrs === { password: 'mypassword' }
// so attrs is copied over to record object to result in { email: "test#test.com", password: 'mypassword' }
Object.assign(record, attrs);
// take array of records and write it back to JSON file
await this.writeAll(records);
}
async getOneBy(filters) {
const records = await this.getAll();
// iterate through the collection of records - for/of loop because iterating through array
for (let record of records) {
let found = true;
// iterate through all key/value pairs of the filters object - for/in because iterating through object
for (let key in filters) {
// receive every key inside the object and can look at the value inside of object with filters[key]
// it means email or password at filters is the same as email password on record
if (record[key] !== filters[key]) {
// if email and password between filters and record do not match then...
found = false;
}
}
// record was found because filters object key/value pairs and record are same
if (found) {
return record;
}
}
}
};
Just one thing. If you are passing an empty array of items, what is that you are excepting from nothing.
cart = await cartsRepo.create({ items: [] });
And last. What kind of dB you are using?
epascarello mentioned that maybe cartsRepo is not returning what I expect which got me thinking into looking at the repository.js file and sure enough the problem was that I forgot to add a return attrs; to the repository.js file:
async create(attrs) {
attrs.id = this.randomId();
const records = await this.getAll();
records.push(attrs);
await this.writeAll(records);
return attrs;
}

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.

$regex requires regular expression error mongodb stitch

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));

Async/await and promises [duplicate]

This question already has answers here:
Using async/await with a forEach loop
(33 answers)
Closed 4 years ago.
I am having an issue with using async/await using node v8.1. It appears my issue is that I am not returning a promise from my async functions. This is causing the flow of the program to run out of order. I thought by making a function async that the function automatically returns a promise, but that is not the case I am running into.
I expect the program below to output:
Validating xlsx file...
(text from validateParsedXlsx)
Adding users to cognito...
(text from addUsersToCognito)
Adding users to dynamodb...
(text from addUsersToDynamodb)
Instead, I get:
Validating xlsx file...
Adding users to cognito...
Adding users to dynamodb...
(text from validateParsedXlsx)
(text from addUsersToCognito)
(text from addUsersToDynamodb)
The issue seems to be pretty obvious, that validateParsedXlsx() addUsersToCognito() and addUsersToDynamodb() are not returning promises. Again, I thought that by using the async keyword, the function automatically took care of this.
Thanks for the help.
Here is my script:
const xlsx = require('xlsx');
const AWS = require('aws-sdk');
AWS.config.update({region: 'us-west-2'});
const documentClient = new AWS.DynamoDB.DocumentClient({convertEmptyValues: true});
async function main(){
if (!process.argv[2]) {
console.log('\nAbsolute filepath missing. Pass the absolute filepath in as command line argument.\n')
process.exit(1);
}
const xlsxFilePath = process.argv[2];
let parsedXlsx = [];
try {
parsedXlsx = parseXlsx(xlsxFilePath);
} catch (error) {
if(error.code === 'ENOENT') {
console.log(`\nThe file path: ${process.argv[2]} cannot be resolved\n`)
} else {
console.log(error);
}
}
console.log('\n\nValidating xlsx file...\n');
await validateParsedXlsx(parsedXlsx);
console.log('\n\nAdding users to cognito...\n');
await addUsersToCognito(parsedXlsx);
console.log('\n\nAdding users to dynamodb...\n');
await addUsersToDynamodb(parsedXlsx);
}
function parseXlsx(filePath) {
const workbook = xlsx.readFile(filePath);
const sheetNameList = workbook.SheetNames;
const parsedXlsxSheets = sheetNameList.map(function (y) {
const worksheet = workbook.Sheets[y];
const headers = {};
const data = [];
for (z in worksheet) {
if(z[0] === '!') continue;
//parse out the column, row, and value
const col = z.substring(0,1);
const row = parseInt(z.substring(1));
const value = worksheet[z].v;
//store header names
if(row == 1) {
headers[col] = value;
continue;
}
if(!data[row]) data[row] = {};
data[row][headers[col]] = value;
}
//drop those first two rows which are empty
data.shift();
data.shift();
return data;
});
return parsedXlsxSheets[0]
}
async function validateParsedXlsx(users) {
let error = false;
users.forEach(async (user, index) => {
if (!user.email) {
console.log(`User at row ${index + 2} doesn't have 'email' entry in xlsx file.`);
error = true;
}
if (!user.displayName) {
console.log(`User at row ${index + 2} doesn't have 'displayName' entry in xlsx file.`);
error = true;
}
if (!user.serviceProviderId) {
console.log(`Userat row ${index + 2} doesn't have 'displayName' entry in xlsx file.`);
error = true;
} else {
const params = {
TableName: 'service-providers',
Key: {
serviceProviderId: user.serviceProviderId
}
}
const response = await documentClient.get(params).promise();
if (!response.Item) {
console.log(`User at row ${index +2} does not have a valid serviceProviderId.`);
error = true;
} else {
console.log(`User ${user.email} is valid, assigned to service provider: ${response.Item.displayName}`);
}
}
if (error) {
console.log(`Every user in xlsx file must have these attributes, spelled correctly: email, displayName, and serviceProviderId\n\nIn addition, make sure the serviceProviderId is correct by checking the service-providers dynanomdb table.`);
process.exit(1);
}
});
}
async function addUsersToCognito(users) {
const cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider();
const results = await cognitoIdentityServiceProvider.listUserPools({MaxResults: 10}).promise();
let serviceProviderUserPoolId = '';
results.UserPools.forEach((userPool) => {
if(userPool.Name === 'service-provider-users') {
serviceProviderUserPoolId = userPool.Id;
}
});
users.forEach(async (user) => {
const params = {
UserPoolId: serviceProviderUserPoolId,
Username: user.email,
DesiredDeliveryMediums: ['EMAIL'],
TemporaryPassword: 'New_User1',
UserAttributes: [
{
Name: 'email',
Value: user.email
},
{
Name: 'custom:service_provider_id',
Value: user.serviceProviderId
}
]
}
try {
await cognitoIdentityServiceProvider.adminCreateUser(params).promise();
console.log(`Added user ${user.email} to cognito user pool`);
} catch (error) {
if (error.code === 'UsernameExistsException') {
console.log(`Username: ${user.email} already exists. No action taken.`);
}
else {
console.log(error);
}
}
});
}
async function addUsersToDynamodb(users) {
users.forEach(async (user) => {
const params = {
TableName: 'service-provider-users',
Item: {
serviceProviderId: user.serviceProviderId,
userId: user.email,
displayName: user.displayName,
isActive: false,
role: 'BASIC'
},
ConditionExpression: 'attribute_not_exists(userId)'
}
try {
await documentClient.put(params).promise();
console.log(`Added user ${user.email} to dynamodb user table`);
} catch (error) {
if (error.code === 'ConditionalCheckFailedException') {
console.log(`User ${user.email} already in the dynamodb table service-provider-users`);
} else {
console.log(error);
}
}
});
}
main();
users.forEach(async (user, index) => {
That starts a few promising actions but never awaits them. May do:
await Promise.all(users.map(async (user, index) => {
... to execute them in parallel or do this:
await users.reduce((chain, user, index) => async (user, index) => {
await chain;
//...
}, Promise.resolve());
To execute them one after another.
PS: Using process.exit should be the very last option to end your program

Categories

Resources