Im completely lost. This is some test code I use to print a specific key of an object, then im printing the entire object.
console.log(docs[0].mc_ign);
console.log(docs[0]);
Now this is the output I see on the console:
The__TxT
{
id: 0,
status: 1,
testing: false,
_id: 5dbc17eb20b3a8594d569570,
timestamp: 2019-11-01T11:32:59.380Z,
mc_uuid: 'dac89e44d1024f3b810478ed62d209a1',
discord_id: '653029505457586176',
email_address: 'gut97930#eveav.com',
country: 'Germany',
birth_month: 3,
birth_year: 1943,
about_me: 'about me text',
motivation: 'motivation text',
build_images: '',
publish_about_me: true,
publish_age: false,
publish_country: true,
__v: 0
}
Where is the mc_ign key?
The object itself comes from mongoose, the missing key is added by me after the fact:
docs[i].mc_ign = mc_ign;
I tried logging the entire object before and after I add the key and assign the value. They are both the same.
What am I missing? Why can I read the value out, but cant see it?
It is mongoose document object. To achieve what you want do the following.
docs[0] = docs[0].toObject();
docs[0].mc_ign = "stuff";
console.log(docs[0])
.toObject() convert it to plain JS object.
Related
I'm trying to update an array (Array name is "Variables" please refer the attached screenshot) which presents inside an Object, so I want to update that array if there is word called "placeholder" in alertMessage(it's a different property presents in the same Object)
I'd appreciate any help on how to update this array in question, I tried using pop method but it didn't go as planned and I've attached screenshots of the Objects for reference
You can retrieve the string placeholder like this data['alertMessage']['en_US']['all'] and then use a conditional statement to make changes to the array inside the data object.
let data = {
alertOne: '',
alertTwo: '',
alertMessage: {
en_US: {all: 'placeholder'}
},
variables: [
{id: 0, uuid: '123'},
{id: 1, uuid: '223'},
{id: 2, uuid: '323'}
]
}
let all = data['alertMessage']['en_US']['all']
// if condition is met add a new object to the array
if(all === 'placeholder'){
data.variables = [...data.variables, {id: 3, uuid: '423'}]
}
console.log(data)
How can I get John, Liza, Peter, outside of the for loop?
var siblings = ["John", "Liza", "Peter"];
for (var i=0; i < siblings.length; i++) {
names = siblings[i];
console.log(names) // correctly outputs John, Liza, Peter
}
console.log(names) // only gives Peter
Update: I was trying to reproduce the problem in a unit test case. But here is the whole thing.
So I made a request, and got an array
[ { kind: 'youtube#video',
etag: '"sZ5p5Mo8dPpfIzLYQBF8QIQJym0/XDKLx9FZygpwjYlzaTU-HAH31tw"',
id: 'b4Bj7Zb-YD4',
snippet:
{ publishedAt: '2016-10-28T07:00:01.000Z',
channelId: 'UCaHNFIob5Ixv74f5on3lvIw',
title: 'Calvin Harris - My Way (Official Video)',
description: 'Calvin Harris - My Way (Official Video)\nDownload My Way: http://smarturl.it/CHMyWay?IQid=yt\nListen to My Way: http://smarturl.it/StreamCH?IQid=yt\n\n---------\n\nFollow Calvin Harris:\nFacebook: https://www.facebook.com/calvinharris/ \nTwitter: https://twitter.com/CalvinHarris \nInstagram: https://www.instagram.com/calvinharris/ \nWebsite: http://calvinharris.com/ \n\n---------\n\nCalvin Harris - My Way (Lyrics)\n\nWhy wait \nTo say\nAt least I did it my way \nLie awake \nTwo faced \nBut in my heart I understand \nI made \nMy move \nAnd it was all about you \nNow I feel \nSo far removed \n\nYou were the one thing in my way \n\nMy way\nAway away away',
thumbnails: [Object],
channelTitle: 'CalvinHarrisVEVO',
tags: [Object],
categoryId: '10',
liveBroadcastContent: 'none',
localized: [Object] },
statistics:
{ viewCount: '8313145',
likeCount: '271119',
dislikeCount: '7364',
favoriteCount: '0' } },
{ kind: 'youtube#video',
etag: '"sZ5p5Mo8dPpfIzLYQBF8QIQJym0/c2pD6DG-ieqcYFEcGjGB31NYRKk"',
id: '0zGcUoRlhmw',
snippet:
{ publishedAt: '2016-10-24T14:00:01.000Z',
channelId: 'UCRzzwLpLiUNIs6YOPe33eMg',
title: 'The Chainsmokers - Closer ft. Halsey',
description: 'Collage EP: \nPre-order on Amazon: http://smarturl.it/CollageAmz\nUrban Outfitters White Vinyl: http://smarturl.it/CollageVinyl\n\n"Closer" ft. Halsey\niTunes: http://smarturl.it/CloseriT\nSpotify: http://smarturl.it/CloserStream\nApple Music: http://smarturl.it/CloserAM\nAmazon: http://smarturl.it/CloserAmz\n\nDirected by: Dano Cerny\n\nFollow The Chainsmokers:\nhttp://www.youtube.com/thechainsmokers\nhttp://www.twitter.com/thechainsmokers\nhttp://www.facebook.com/thechainsmokers\nhttp://www.instagram.com/thechainsmokers\nhttp://www.soundcloud.com/thechainsmokers\n\nFollow Halsey:\nTwitter: http://twitter.com/halsey\nFacebook: https://www.facebook.com/HalseyMusic\nInstagram: http://instagram.com/iamhalsey\nSpotify: http://smarturl.it/HalseySpotify\nNewsletter: http://www.iamhalsey.com/mailinglist\nPurchase Music: http://www.iamhalsey.com/badlandsbox',
thumbnails: [Object],
channelTitle: 'ChainsmokersVEVO',
tags: [Object],
categoryId: '10',
liveBroadcastContent: 'none',
localized: [Object] },
statistics:
{ viewCount: '21315027',
likeCount: '573642',
dislikeCount: '19913',
favoriteCount: '0',
commentCount: '40899' } }
]
So I put this in a variable e.g. siblings. And I loop through the entire array, to get snippet.title, snippet.publishedAt. Everything is good so far. But I want to push it into a new array, and make it available for use OUTSIDE of the loop.
My code as of now:
listVideos is the chunk I pasted before.
listVideos.forEach(function list(item) {
data = new Array();
title = item.snippet.title;
return data.push(title);
});
console.log(data); // only gives first title. I want to get all titles in an array stored inside data. And make data available globally
setting the variable var data in the beginning does not work for me, because I have other functions outside of the forEach loop. Therefore, it has to be a flexible way which I can move anywhere I want, such as some kind of function scope.
Thanks.
It only says Peter because each loop iteration you're setting 'names' to that particular name. If you want to get ALL the names, then 'names' has to be an array and you should push the names in during the loop:
names.push(siblings[i])
var names = new Array();
names.push(siblings[i]);
console.log(names);
you don't need loop:
var siblings = ["John", "Liza", "Peter"];
var str = siblings.join(',');
console.log(str); //John,Liza,Peter
I'm writing a route in Express (Node.js) in which i pull some data from mongoose. Let's say that at some some point I need to compare if employee._id is in array of bad employees id::
let employees = await EmployeeModel.find().exec();
employees.forEach(function (employee) {
if (arrayOfBadEmployees.indexOf(employee._id) !== -1) {
employee.isBad = true;
}
});
console.log(employees);
console.log(employees[0].isBad);
and here's my output:
[ { __v: 0, name: 'Employee X', _id: 1 },
{ __v: 0, name: 'Employee Y', _id: 3 },
{ __v: 0, name: 'Employee Z', _id: 5 } ]
true
So when I can't see 'isBad' property when I console.log the whole array/object, but this property is still there? When i check with propertyIsEnumerable('isBad') it says true.
Mongoose, by default, returns an instance of MongooseDocument, which doesn't expose your data directly and adds convenience methods like populate or save
You can use the lean option to get raw objects instead.
MongooseDocument also exposes a toObject function if you need to get editable documents.
I am trying to push some things onto a Mongoose model. The model looks like this.
var ScheduleSchema = new mongoose.Schema({
hours: Number,
items: [{number: Number, minutes: Number, details: {description: String}, type: String}],
userId: Number
});
//later
ScheduleSchema.methods.createNew = function(hours, tasks, breathers) {
var schedule = makeSchedule(hours, tasks, breathers);
console.log(schedule);
this.items = schedule;
console.log(this.items);
}
I think that is enough code for my issue, but I can give more code if needed. Essentially, I've got a method for creating a schedule and then I want to assign the schedule to the object's 'items' property. I must admit I am still learning about mongoose so it is likely a problem there.
Anyway, I know my makeSchedule function is working, because I see this as the output from the first console message.
[{ number: 1,
minutes: 30,
details: {description: 'Task A'},
type: 'task'},
{ number: 2,
minutes: 45,
details: {description: 'Task B'},
type: 'task'},
etc...
]
However, when the console output from my second log statement, this.items, prints, I don't see the same structure. Instead, I see
["[object Object]", "[object Object]", "[object Object]", etc...]
Why am I not able to just assign the schedule variable to this.items? I believe I was even able to do it before, but I made some changes to my schedule code and now I cannot.
That would lead me to believe that the error is in my schedule code, but as you can see, it is creating the list of items just fine, based on the console output. Can anyone see a really obvious, potentially mongoose related mistake that I may have missed as a rookie?
My guess is that you recently added the type field to the embedded objects in items which is making Mongoose now think that items contains an array of strings instead of an array of objects like you have.
To fix it, use an object to define the type for type in your schema like so:
var ScheduleSchema = new mongoose.Schema({
hours: Number,
items: [{
number: Number,
minutes: Number,
details: {description: String},
type: {type: String}
}],
userId: Number
});
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