I create a database (wordinfo - nedb in memory), insert some data, and then retrieve the data (sorted) for print out with console.log. Too easy. Curiously, the console.log printout changes with the addition of a string:
wordinfo.find( { $and: [{index: {$lte: 10}},{index: {$gt: 5}}] }).sort({index: 1}).exec(function(err,docs) {
console.log(docs);
});
Which yields on the console:
11 Mar 09:51:46 - [nodemon] starting `node app.js`
Running myscripts
Express server listening on port 3000
[ { index: 6, value: 'Artistic', _id: 'XfudVdremMDODJWk' },
{ index: 7, value: 'Assertive', _id: 'utiSSGqGDwlD1olv' },
{ index: 8, value: 'Assessing', _id: 'zzhmecUhkUvCfnNA' },
{ index: 9, value: 'Autonomous', _id: 'QPGOZRXv48c9hvhV' },
{ index: 10, value: 'Blunt', _id: 'hrEBQ7tAXuZLAzSk' } ]
Now I change the print out request to include a little string identifying what is printing out ("Word info: ") like so:
wordinfo.find( { $and: [{index: {$lte: 10}},{index: {$gt: 5}}] }).sort({index: 1}).exec(function(err,docs) {
console.log('Word info: ' + docs);
});
Which yields something different on the console:
11 Mar 09:52:14 - [nodemon] starting `node app.js`
Running myscripts
Express server listening on port 3000
Word info: [object Object],[object Object],[object Object],[object Object],[obje
ct Object]
The 'docs' variable now prints out as the type of each record (object) instead of the content. Why? What is causing the change? Not a biggie, just curious. TIA for the assistance.
This is because you passed a string to console.log().
Console.log() accepts the docs object you used in your first example, however in your second example you concatenated your object with a string; console.log('Concatenation happens here' + docs), now the function doens't format your object as you wanted.
To correctly log an object pass them to the function: console.log('Word info: ', docs)
You can also format using %j: console.log('These objects were found: %j \n Yay!', docs)
Reference: https://developer.mozilla.org/en-US/docs/Web/API/console.log
Related
Error HH8: There's one or more errors in your config file:
Invalid account: #0 for network: mumbai - Expected string, received undefined
Invalid account: #0 for network: mainnet - Expected string, received undefined
To learn more about Hardhat's configuration, please go to https://hardhat.org/config/
Neither two previous answers worked for me:
* Invalid account: #0 for network: mumbai - Expected string, received undefined
H88 Error: Invalid account: #0 for network: mumbai - Expected string, received undefined
Ended up with same error as before.
This is my hardhat.config.js:
const fs = require('fs'); //allow to read from local file system
const projectId = fs.readFileSync(".secret").toString().trim() || "";//kept real source code of "projectId" out for this question asking
module.exports = {
defaultNetwork: "hardhat",
networks: {
hardhat: {
chainId: 1337
},
mumbai: {
url: `https://polygon-mumbai.infura.io/v3/${projectId}`,
url: "https://rpc-mumbai.matic.today",
accounts: [process.env.privateKey]
},
mainnet: {
url: `https://polygon-mainnet.infura.io/v3/${projectId}`,
url: "https://polygon-rpc.com/",
accounts: [process.env.privateKey]
},
},
solidity: {
version: "0.8.17",
settings: {
optimizer: {
enabled: true,
runs: 200
}
}
}
}; ```
Posting an update to my own question. I checked my .secret file again. I had messed up with the format there by having pressed enter too many times. It was reading it as "extra characters" when it is supposed to be exactly 32 bytes(64 characters). Super rookie mistake. Thank you to those that tried to help me.
I'm currently writing a small Twitter app using the Twit API. To do what I need to do, I'd like the data to be able to be filtered by user id, and not get all the other garbage JSON spits out. Here's what the response looks like:
{ created_at: 'Sat Jun 23 03:45:13 +0000 2018',
id: 1010368149466697700,
id_str: '1010368149466697728',
text:
'RT #ClassicIsComing: "Let\'s Talk ETC!" Podcast Series by #chris_seberino of #InputOutputHK \nA deep series of powerful intervie
ws with influ…',
truncated: false,
entities:
{ hashtags: [],
symbols: [],
user_mentions: [ [Object], [Object], [Object] ],
urls: [] },
source:
'TweetDeck',
in_reply_to_status_id: null,
in_reply_to_status_id_str: null,
in_reply_to_user_id: null,
in_reply_to_user_id_str: null,
in_reply_to_screen_name: null,
user:
{ id: 759252279862104000,
id_str: '759252279862104064',
name: 'Ethereum Classic',
screen_name: 'eth_classic',
location: 'Blockchain',
description:
'Latest News and Information from Ethereum Classic (ETC). A crypto-currency with smart contracts which respects immutability a
nd neutrality.',
url: ,
entities: { url: [Object], description: [Object] },
protected: false,
followers_count: 216255,
friends_count: 538,
listed_count: 2147,
etc. The code i'm using to get this is:
T.get('statuses/home_timeline', {count: 1, exclude_replies: true},
function(err, data, response){
if (err){
console.log('Uh oh, we got a problem');
}
else{
console.log('We GUUCie bruh');
}
var tweets = data;
/* for (var i = 0; i < tweets.length; i++) {
console.log(tweets[i]);
} */
console.log(data);
});
the last block of code is commented out because I've attempted to define "tweets" as data.id, data.statuses.id, etc, but everything seems to spit out "undefined." I'm a complete noob to javascript and JSON as I'm only currently learning C++ # school, so any help would be appreciated!
edit
I thought I'd add in the error message to show you what happens when I try to treat the data as an object.
If I try to use JSON.parse(data) as the value for my tweet variable:
T.get('statuses/home_timeline', {count: 1, exclude_replies: true}, callBackFunction)
function callBackFunction(err, data, response){
if (err){
console.log('Uh oh, we got a problem');
}
else{
console.log('We GUUCie bruh');
}
var tweets = JSON.parse(data);
//for (var i = 0; i < tweets.length; i++) {
// console.log(tweets[i].id_str);
// }
console.log(tweets.id_str);
}
I get:
$ node crypt.js
the bot is starting
We GUUCie bruh
undefined:1
[object Object]
^
SyntaxError: Unexpected token o in JSON at position 1
at JSON.parse (<anonymous>)
If I try to treat it as an object right away, with:
function callBackFunction(err, data, response){
if (err){
console.log('Uh oh, we got a problem');
}
else{
console.log('We GUUCie bruh');
}
var tweets = data.id_str;
//for (var i = 0; i < tweets.length; i++) {
// console.log(tweets[i].id_str);
// }
console.log(tweets);
}
I get:
$ node crypt.js
the bot is starting
We GUUCie bruh
undefined
Have you tried JSON.parse?
So your line "var tweets = data;" would be "var tweets = JSON.parse(data);"
From there you should be able to interact with the data as if it were an object and grab specifically the id or whatever you're looking for.
I'm also a noob, so I don't have an in depth explanation as to why this works, but it helped fix an issue I had when pulling data from API.
I'm trying to do an upsert where I $push a new element onto a field that is an array.
However, whenever I use $push I get the error telling me that I'm not allowed to use $ at the beginning of operators.
Here's the debug trace:
loopback:connector:mongodb create +3s ThingUser { user: 'gerald', '$push': { things: 'hats' } }
loopback:connector:mongodb MongoDB: model=ThingUser command=insert +2ms [ { user: 'gerald', '$push': { things: 'hats' }, _id: undefined },
{ safe: true },
[Function] ]
loopback:connector:mongodb Error: +5ms { [MongoError: key $push must not start with '$']
name: 'MongoError',
message: 'key $push must not start with \'$\'' }
loopback:connector:mongodb create.callback +0ms ThingUser { [MongoError: key $push must not start with '$']
name: 'MongoError',
message: 'key $push must not start with \'$\'' } null
It seems as though I'm not putting allowExtendedOperators in the correct place. I have tried everywhere where does this thing go? Can it not work with upsert?
I'm trying make CRUD operation in Electron, where using MongoDB, and Mongoose for Electron connect to database.
I have a function list for return the "return" of Mongoose. When I debugging return data, is show correct in my terminal
ipc.on('products.list', function(event, query) {
Service.list(query, function(err, data) {
console.log(data); // this will be print correct result
event.sender.send('product.list', data);
});
});
Result of code upper part:
[ { _id: 55c15f2981260a6f0ef8a657,
__v: 0,
deleted_at: '',
updated_at: '',
created_at: Tue Aug 04 2015 21:51:52 GMT-0300 (BRT),
measure: '',
aplication: '',
model: 'Mode XBA',
reference: 'Reference test 123',
code: '2028' } ]
But when I debug return data by client side with fallowing code, result is not correct and is not equal server side print.
Client side code:
ipc.on('product.list', function(data) {
window.data = data;
console.log(data); // this will print incorrect result
});
ipc.send('products.list', {});
Result of client side received:
{
"$__":{....},
"_doc":{...},
"_posts":{...},
"_pres":{...},
"isNew":false
}
Contains more objects in each element.
Why this happens? How to can I resolve this problem?
I resolved this problem!
This return is result from Mongoose
{
"$__":{....},
"_doc":{...},
"_posts":{...},
"_pres":{...},
"isNew":false
}
For return only property, is need add options {lean : true}
Ex:
Model.find(this.query)
.lean()
.exec(function(err, data) {}
);
More detail in Mongoose Doc
I've got an issue reading a nested array from JSON(BSON from MongoHQ) using Node and Angular.
JSON snippet: http://pastie.org/9305682. Specifically look for the edges array.
Mongoose model: http://pastie.org/9305685
Basically I call the character from the DB and then attempt to log it to the console with
console.log(char); before sending it back to the angular call with res.json(char); 'char' is the returned character from the databased saved as my mongoose model.
Attempting to log the character to the console. I get everything looking normal except for the portions with the nested "effects" arrays. Anywhere they show up I receive the following:
edges:
[ { name: 'Super Hacker', notes: '', effects: [Object] },
{ name: 'Witty', notes: '', effects: [Object] },
{ name: 'Attractive', notes: '', effects: [Object] },
{ name: 'Encyclopedic Memory',
notes: 'Prereq: d8 Smarts',
effects: [Object] },
{ name: 'Daywalker', notes: '', effects: [Object] },
{ name: 'Tough', notes: '', effects: [Object] } ],
From here if I try to call it with:
From NodeJS - console.log(char[0].edges[0].effects[0].type); - Returns undefined.
From Angular View - {{cur_char.edges[0].effects[0].type}} - Displays nothing.
Thanks in advance for the help. Let me know if I can provide more in.
I think what you're asking is how to see more depth to the object in the console output. You can use util.inspect to print out more information:
console.log(util.inspect(char, { depth: 5 }));
By default util.inspect only goes to a depth of 2 which explains why you can only see the contents of the array (1) and the primitive properties of each element in the array (2).
See: http://nodejs.org/api/util.html#util_util_inspect_object_options