undefined in TypeORM and NestJS - sqlite

var name = await this.productRepo.findOne({where:{id}})['name']
Hi guys. I use typeorm and sqlite to get the property name from ProductEntity but I get undefined instead.
when I try to run var name = await this.productRepo.findOne({where:{id}}) i get something like that
ProductEntity {
id: 1,
name: 'فن لپتاپ',
code: 'a57gr3f',
quantity: 2,
discription: 'ب',
price: 3000000
}
I am expected to get a فن لپتاپ instead of undefined
I'll be thankfull if you help.

await this.productRepo.findOne({where:{id}})['name']
// \____________________________________/
// this is an instance of Promise, not the resolved value
// and Promise doesn't have the property 'name'
do this instead:
( await this.productRepo.findOne({where:{id}}) )['name']

Related

Cannot read properties of undefined (reading '_hex') Next js buyNft

so I am building an nft marketplace and everything is good with creating nft .. etc but when attempting to buy an nft I get this error :
ethers.umd.js?e6ac:4395 Uncaught (in promise) TypeError: Cannot read properties of undefined (reading '_hex')
Here is the code snippet:
const buyNft = async (nft) => {
const web3Modal = new Web3Modal();
const connection = await web3Modal.connect();
const provider = new ethers.providers.Web3Provider(connection);
const signer = provider.getSigner();
const contract = new ethers.Contract(
MarketAddress,
MarketAddressABI,
signer
);
const price = ethers.utils.parseUnits(nft.price.toString(), "ether")
console.log(price)
// code stops here
const transaction = await contract.createMarketSale(nft.tokenId, {
value: price,
});
await transaction.wait();
};
when debugging seems that the code stops before the transaction constant.
when console .log the price I get this:
I tried to remove the toString method, also tried to spread the price object in transaction variable like this value:{...price} but still didn't work
The createMarketSale() first agument expects a BigNumber instance (or a stringified number that it would convert to BigNumber).
When you pass it undefined, it throws the error mentioned in your question.
Solution: Make sure that your nft.tokenId is either a BigNumber or string - not undefined.

error: `Uncaught (in promise) TypeError: Cannot read property 'doc' of undefined`

eerror: Uncaught (in promise) TypeError: Cannot read property 'doc' of undefined
actions: {
async register({ dispatch }, form) {
//sign up user
const { user } = await fb.auth.createUserWithEmailAndPassword(form.email, form.password)
// create user profile object
await fb.usersCollection.doc(user.uid).set({
name: form.name
})
//fetch user profile
dispatch('fetchUserProfile', user)
},
help find the problem pls Where a can define doc ? Or where is mistake ?
If you get the error
Cannot read property 'XXX' of undefined
check your value before the dot ".XXX" eg.
fb.usersCollection.doc
console.log(fb.usersCollection) // undefined
Your fb.usersCollection has an "undefined" value because fb doesn't contain any usersCollection. If you wanna access your firebase "users" collection you have to do
fb.collection('users').doc(...);
checkout firebase documentation
You need something like
import { fb, db } from '#/modules/firebase'
...
await db.collection('users').doc(user.uid).set({
name: form.name
})

Do CosmosDB Mongo API compound unique indexes require each field to be unique?

I'm trying to set up a collection of versioned documents in which I insert a new document with the same id and a timestamp whenever there's an edit operation. I use a unique compound index for this on the id and timestamp fields. CosmosDB is giving me MongoError: E11000 duplicate key error whenever I try to insert a document with a different id but an identical timestamp to another document. The MongoDB documentation says that I should be able to do this:
https://docs.mongodb.com/v3.4/core/index-unique/#unique-compound-index
You can also enforce a unique constraint on compound indexes. If you use the unique constraint on a compound index, then MongoDB will enforce uniqueness on the combination of the index key values.
I tried using a non-unique index but the Resource Manager template failed, saying that non-unique compound indexes are not supported. I'm using the node.js native driver v3.2.4. I also tried to use Azure Portal to insert documents but received the same error. This makes me believe it's not a problem between CosmosDB and the node.js driver.
Here's a small example to demonstrate the problem. I'm running it with Node v10.15.3.
const { MongoClient } = require('mongodb');
const mongoUrl = process.env.COSMOSDB_CONNECTION_STRING;
const collectionName = 'indextest';
const client = new MongoClient(mongoUrl, { useNewUrlParser: true });
let connection;
const testIndex = async () => {
const now = Date.now();
connection = await client.connect();
const db = connection.db('master');
await db.collection(collectionName).drop();
const collection = await db.createCollection(collectionName);
await collection.createIndex({ id: 1, ts: -1 }, { unique: true });
await collection.insertOne({ id: 1, ts: now, title: 'My first document' });
await collection.insertOne({ id: 2, ts: now, title: 'My other document' });
};
(async () => {
try {
await testIndex();
console.log('It works');
} catch (err) {
console.error(err);
} finally {
await connection.close();
}
})();
I would expect the two insert operations to work and for the program to exit with It works. What I get instead is an Error:
{ MongoError: E11000 duplicate key error collection: master.indextest Failed _id or unique key constraint
at Function.create (/home/node/node_modules/mongodb-core/lib/error.js:43:12)
at toError (/home/node/node_modules/mongodb/lib/utils.js:149:22)
at coll.s.topology.insert (/home/node/node_modules/mongodb/lib/operations/collection_ops.js:859:39)
at handler (/home/node/node_modules/mongodb-core/lib/topologies/replset.js:1155:22)
at /home/node/node_modules/mongodb-core/lib/connection/pool.js:397:18
at process._tickCallback (internal/process/next_tick.js:61:11)
driver: true,
name: 'MongoError',
index: 0,
code: 11000,
errmsg:
'E11000 duplicate key error collection: master.indextest Failed _id or unique key constraint',
[Symbol(mongoErrorContextSymbol)]: {} }
Is this expected behavior or a bug in CosmosDB's MongoDB API?

Sinon stub - Cannot destructure property 'x' of 'undefined' or 'null'

I need to stub the following with Sinon :
const { clientId, dateString } = await parameterParser.prepareInputParameters(con, req);
I have tried using the following:
const retData = {
clientId: 872,
dateString: '1970-01-01',
};
sandbox.stub(parameterParser, 'prepareInputParameters').withArgs(con, req).returns(retData);
but I get the error:
TypeError: Cannot destructure property 'clientId' of 'undefined' or 'null'.
I have successfully stubbed the following elsewhere in my tests:
const { retData } = await sqlFileReader.read('./src/database/sql/getClientIdFromLoanId.sql', [`${req.query.loan_id}`], con, req.logger);
by using:
const retData = {
rowsCount: 1,
rows: [{ client_id: 872 }],
};
sandbox.stub(sqlFileReader, 'read').returns({ retData });
but I cannot get my head round how to stub const { clientId, dateString }
You need to be using resolves instead of returns for these stubs, since you are awaiting their return values, which should actually be Promises that resolve with your retData, and not the retData itself.
In sinon, resolves is a convenience for asynchronous methods. The following two lines are similar:
sinon.stub(foo, 'bar').returns(Promise.resolve('baz'));
sinon.stub(foo, 'bar').resolves('baz');
Your second sample may not be throwing an error, but if you log the value of retData after this line:
const { retData } = await sqlFileReader.read('./src/database/sql/getClientIdFromLoanId.sql', [`${req.query.loan_id}`], con, req.logger);
You'll notice that it is undefined. This is because await causes the result of the method call to be a Promise, which does not have a property called retData.
As for why your first sample is behaving differently, I'm not sure. I suspect that there's something else going on that isn't evident from your samples. Would you mind sharing more code?

Meteor how to get the result of Collection.update on success or failure?

I have a collection that is getting updated in an event handler and which is updating the collection and I would like to get the result of the update if it was a success or failure so I can do some logic based on its result. i.e. reset session values etc.
I have always been just testing the db action itself inside of an if block for inserts which worked fine however this does not seem to be working for update.
Template.customers_update.events({
'click a#cancel, click button#close' : function(event) {
event.preventDefault();
Session.set("editCustomer", false);
Session.set("customerId", null);
},
'click input[type=submit], submit form#create_customer' : function (event) {
event.preventDefault();
var customer_name = $("#customer_name").val();
var customer_address = $("#customer_address").val();
var customer_city = $("#customer_city").val();
var customer_state = $("#customer_state").val();
var customer_zip = $("#customer_zip").val();
var customer_phone = $("#customer_phone").val();
var customer_fax = $("#customer_fax").val();
var customer_eda = $("#eda_number").val();
var customer_duns = $("#duns_number").val();
if (Customers.update(Session.get("customerId"), {$set: {user_id: Meteor.user()._id, name: customer_name, address: customer_address, city: customer_city, state: customer_state, zip: customer_zip, phone: customer_phone, fax: customer_fax, eda_number: customer_eda, duns_number: customer_duns}})) {
console.log("Update Sucsess");
Session.set("editCustomer", false);
Session.set("customerId", null);
}
}
});
and in the server it is set to allow and return true
Customers.allow({
insert: function (userID, customer) {
return userID === customer.user_id;
},
update: function (userID, customer) {
return userID === customer.user_id;
},
remove: function (userID, customer) {
return userID === customer.user_id;
}
});
Use the third argument callback (docs)
callback Function
Optional. If present, called with an error object as its argument.
Your code is probably not working because the .update() only throws an exception on the server. From the docs:
On the server, if you don't provide a callback, then update blocks until the database acknowledges the write, or throws an exception if something went wrong. If you do provide a callback, update returns immediately. Once the update completes, the callback is called with a single error argument in the case of failure, or no arguments if the update was successful.
On the client, update never blocks. If you do not provide a callback and the update fails on the server, then Meteor will log a warning to the console. If you provide a callback, Meteor will call that function with an error argument if there was an error, or no arguments if the update was successful.
Change it to:
var updateQuery = {$set: {user_id: Meteor.user()._id, name: customer_name, address: customer_address, city: customer_city, state: customer_state, zip: customer_zip, phone: customer_phone, fax: customer_fax, eda_number: customer_eda, duns_number: customer_duns}}
Customers.update(Session.get("customerId"), updateQuery, function (error) {
//on error do this
});

Resources