Logging JSON body works, but not body.item. Gives undefined - json

This function creates a playlist using the Spotify API. Which returns a body containing an 'id' that I need.
function createPlaylist(pc) {
let index = partyCodeExists(pc)
let at = token_arr[index]
let userID = user_ids[index]
var authOptions = {
url: 'https://api.spotify.com/v1/users/' + userID + '/playlists',
body: JSON.stringify({
'name': pc,
'description': 'Jukibox playlist',
'public': false
}),
dataType: 'json',
headers: {
'Authorization': 'Bearer ' + at,
'Content-Type': 'application/json'
}
};
request.post(authOptions, function (error, response, body) {
console.log(body);
console.log(body.id);
});
};
The lower console logs give the following output:
{
"collaborative" : false,
"description" : null,
"external_urls" : {
"spotify" : "https://open.spotify.com/user/larsonadam-us/playlist/5pZ3C6ZRB3C9Tv9Z3EdA0g"
},
"followers" : {
"href" : null,
"total" : 0
},
"href" : "https://api.spotify.com/v1/users/larsonadam-us/playlists/5pZ3C6ZRB3C9Tv9Z3EdA0g",
"id" : "5pZ3C6ZRB3C9Tv9Z3EdA0g",
"images" : [ ],
"name" : null,
"owner" : {
"display_name" : null,
"external_urls" : {
"spotify" : "https://open.spotify.com/user/larsonadam-us"
},
"href" : "https://api.spotify.com/v1/users/larsonadam-us",
"id" : "larsonadam-us",
"type" : "user",
"uri" : "spotify:user:larsonadam-us"
},
"primary_color" : null,
"public" : true,
"snapshot_id" : "90UhGQhCi0Xq2vch8g/wrQ5BZoKK5cmIkiwybqJLUIsEAljI+L90YPzpD59T8zwP",
"tracks" : {
"href" : "https://api.spotify.com/v1/users/larsonadam-us/playlists/5pZ3C6ZRB3C9Tv9Z3EdA0g/tracks",
"items" : [ ],
"limit" : 100,
"next" : null,
"offset" : 0,
"previous" : null,
"total" : 0
},
"type" : "playlist",
"uri" : "spotify:user:larsonadam-us:playlist:5pZ3C6ZRB3C9Tv9Z3EdA0g"
}
undefined
Why does the second option display undefined?
Another note, I have body parser and it works in other areas of the code

The problem is that the return is a string. You need to handle the return before you get the ID. Try this.
console.log(body)
let bodyObject = JSON.parse(body)
console.log(bodyObject.id)

Related

Angular json, filter unwanted json fields

I have an json from backend:
{
"_embedded" : {
"countries" : [ {
"id" : 1,
"name" : "Brazil",
"code" : "BR",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/countries/1"
},
"country" : {
"href" : "http://localhost:8080/api/countries/1"
},
"states" : {
"href" : "http://localhost:8080/api/countries/1/states"
}
}
}, {
"id" : 2,
"name" : "Canada",
"code" : "CA",
"_links" : {
"self" : {
"href" : "http://localhost:8080/api/countries/2"
},
"country" : {
"href" : "http://localhost:8080/api/countries/2"
},
"states" : {
"href" : "http://localhost:8080/api/countries/2/states"
}
}
}
}
}
And on frontend, I want to get data according to typescript interface:
interface Country {
id: number;
code: string;
name: string;
}
I have a code which maps above json to interface:
getCountries(): Observable<Country[]> {
return this.httpClient.get<CountriesResponse>(this.countriesUrl).pipe(
map(response => <Country[]>response._embedded.countries)
)
}
interface CountriesResponse {
_embedded: {
countries: Country[]
}
}
But after mapping method still returns data which is not present in typescript interface Country, I mean _links field.
Please suggest how to avoid it.
I actually found some solution but still thinks it could be done better:
getCountries(): Observable<Country[]> {
return this.httpClient.get<CountriesResponse>(this.countriesUrl).pipe(
map(response => {
const data: Country[] = response._embedded.countries
return data.map(c => ({
id: c.id,
name: c.name,
code: c.code
}))
})
)
}

iterating objects as array of objects sent through postman tool and saving in db

this is the value i'm sending through postman tool
{
"name" :[
{
"first_name" : "antony",
"second_name" : "grijan"
},{
"first_name" : "suresh",
"second_name" : "muthu"
}],
"allergy" : [
{
"condition" : "headache"
},
{
"condition" : "toothache"
}],
"communication" : [
{
"address" : "no 21 big street",
"phone" : "84"
},
{
"address" : "no 43 small street",
"phone" :"87"
}]
}
I got the value in my control layer and i'm trying to save it in my mongodb using mongoose, my model code is
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var patientSchema = new Schema({
name: {
first_name : { type : String, default : ''},
second_name : { type : String, default : ''}
},
allergy : {
condition : {type : String, default : ''}
},
communication : {
address : {type : String, default : ''},
phone : {type : String, default : ''}
}
});
var patients = mongoose.model('Patients',patientSchema);
module.exports = patients;
My service layer code where i'm iterating is
var addDao = require('../dao/dao');
var async = require('async');
module.exports.addPatient = function(detail,callback) {
async.mapValues(detail,function(value,key,callback){
addDao.addPatient(value,function(data){
console.log(data);
console.log("calling");
callback(null, data);
})
}, function(err, result) {
// result is now a map of results for each key
console.log("inside func",result);
callback(result);
}
);
}
I have a console.log() in my service layer but it gives me only empty values, i think there is something wrong either with my model code or my iteration in my service layer!

saving in the database variable as ObjectID() MongoDB, NodeJS

I created function which is adding people_id inside array of given card. But there is problem that inserted id is always not as an objectId() where I just need it to be saved as objectId.
When id is added to array i I'm sending whole variable board JSON to nodejs API where is executed function findOneAndUpdate. And here is problem because after saved this arrays is not objectID in Author. Can someone tell me how to make it?
JSON board
{
"_id" : ObjectId("59e096a7622a3825ac24f343"),
"name" : "1",
"users" : [
ObjectId("59cd114cea98d9326ca1c421")
],
"lists" : [
{
"list" : "1",
"cards" : [
{
"name" : "2",
"Author" : [
"59df60fb6fad6224f4f9f22d",
"59df60fb6fad6224f4f9f22d",
"59df60fb6fad6224f4f9f22e"
]
},
{
"name" : "3",
"Author" : []
}
]
},
{
"list" : "fea",
"cards" : [
{
"name" : "card",
"Author" : []
}
]
}
],
"__v" : 0 }
Router:
router.post('/add/member', function (req, res, next) {
console.log(req.body)
Board.findOneAndUpdate({ _id: req.body._id },
{
$set: {
lists : req.body.lists
}
},
{
upsert: true
},
((cards) => {
res.send(cards)
})
)
});
model:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var BoardSchema = new Schema({
name: { type: String, maxlength: 20 },
lists : { type: Array },
users : [{ type : Schema.Types.ObjectId, ref: 'User' }],
});
module.exports = mongoose.model('Board', BoardSchema);
And here is function with adding poeple
$scope.addMemberToCard = (indexList, indexCard, member) => {
$scope.board.lists[indexList].cards[indexCard].Author.push(member);
console.log( $scope.board.lists[indexList].cards[indexCard].Author)
return ApiService.staff.addMemberToCard($scope.board).then(function () {
})
}
You could use the mongoose Types ObjectID method and then transform the string sent into an ObjectID.
const id = new new mongoose.Types.ObjectId(Author);

Why dose the mongodb returns circular object even though the inserted object is not a circular one

I Am a newbie in MEAN-stack applications, I was trying to create one social media application in mean-stack. I created UserModel.js file to keep the user whole details which is given below,
UserModel.js file
var Address = {
pincode : "",
post : "",
city : "",
district : "",
state : "",
country : "",
};
var Privacy = {
public :true,
friendsOnly : false,
friendsOfFriendsOnly:false,
ImagepostPrivacy : false
};
var Education = {
primarySchool : "",
highSchool : "",
higherSecondary : "",
college : "",
};
var UserModel = {
id : "",
name : "",
lastname : "",
age : 0,
email:"",
phone:"",
username : "",
password : "",
active : true
};
function getUserModel(){
return{
userBasicDetails : UserModel,
userAddress : Address,
userPrivacy : Privacy,
userEducation : Education,
userFollowings : [],
userFollowers : [],
userFriends : []
}
};
module.exports.Usermodel = getUserModel;
I considered it as a POJO class of java, then In userService.js file I accessed this object and assigned the req.body() 's corressponding values to Usermodel and there I converted this Usermodel object to json and which worked as expected.
code for creating and inserting object for 'users' collection,
var userModel = require("../../../models/UserModel");
var con = require("../../database/DbConnection");
var userObject = null;
function registerNewUser(registerdata,callback) {
if(!validateInitialRegisteration(registerdata)){// some validation stuff
return callback(new Error("Invalid data"));
}else{
userObject = createUsedrObject(registerdata);
console.log("object before insertion %j",userObject);// got converted json
con.database().collection('users',function (err,usersCollection) {
usersCollection.insert(userObject,{w:1},function (err) {
if(err){
console.log("error %j",err);
callback(err,null);
}else{
callback(null,userObject);
}
})
});
}
}
/**
*This function will make the user collection object
**/
function createUsedrObject(obj){
var userObject = userModel.Usermodel();
userObject.userBasicDetails.name = obj.firstname;
userObject.userBasicDetails.password = obj.password;
userObject.userBasicDetails.username = obj.username;
return userObject;
}
And I got inserted the object to my 'users' named collection, Then I wrote function to retrieve data from 'users' named collection
function loginCheck(credentials,callback){
if(!credentials){
return callback(new Error("Invalid data"));
}else{
con.database().collection('users',function (err,usersCollection) {
if(err){
return callback(err,null);
}
else{
console.log("fetched data %j",usersCollection.find()); // here I am getting a log like 'fetched data [Circular]'
//callback(null,usersCollection.find());
}
});
}
};
expected json i consoled before insertion is given bellow
{ userBasicDetails:
{ id: '',
name: 'vishnu',
lastname: '',
age: 0,
email: '',
phone: '',
username: 'kr.vishnu401#gmail.com',
password: '1234',
active: true },
userAddress:
{ pincode: '',
post: '',
city: '',
district: '',
state: '',
country: '' },
userPrivacy:
{ public: true,
friendsOnly: false,
friendsOfFriendsOnly: false,
ImagepostPrivacy: false },
userEducation:
{ primarySchool: '',
highSchool: '',
higherSecondary: '',
college: '' },
userFollowings: [],
userFollowers: [],
userFriends: [] }
and the collection in db is
> db.users.find({"_id":ObjectId("581ae4994878ad1a84fa0c77")})
{ "_id" : ObjectId("581ae4994878ad1a84fa0c77"), "userBasicDetails" : { "id" : "", "name" : "vishnu", "lastname" : "", "age" : 0, "email" : "", "phone" : "", "username" : "vishnu#gmail.com", "password" : "123456", "active" : true }, "userAddress" : { "pincode" : "", "post" : "", "city" : "", "district" : "", "state" : "", "country" : "" }, "userPrivacy" : { "public" : true, "friendsOnly" : false, "friendsOfFriendsOnly" : false, "ImagepostPrivacy" : false }, "userEducation" : {"primarySchool" : "","highSchool" : "", "higherSecondary" : "", "college" : ""}, "userFollowings" : [ ], "userFollowers" : [ ], "userFriends: [ ] }
Since it is in Circular type I am not able to convert this object to json, but the inserted object I converted to json before db operation. I think somewhere I messed the concepts. If you have faced same problem please let me know.
usersCollection.find() is a function that takes a callback
try this instead
usersCollection.find().toArray(function(e, users) {
if (e) {
return callback(e, null);
}
console.log(users);
callback(null, users);
});
Documentation: https://mongodb.github.io/node-mongodb-native/api-generated/collection.html

retrieve an element from a json list with angularjs

I have this list JSON:
[{
"password" : "ppp",
"function" : 0,
"id" : 1,
"login" : "ness",
"nom" : "nesrine",
"mail" : "nes#gmail",
"tel" : "238555555"
},
{
"password" : "pass",
"function" : 0,
"id" : 2,
"login" : "bilel.troudi",
"nom" : "bilel",
"mail" : "bilel.troudi91#gmail",
"tel" : null
},
{
"password" : "undefined",
"function" : 1,
"id" : 4,
"login" : "undefined",
"nom" : "ahmed",
"mail" : "ahmed#gmail.com",
"tel" : "221474"
},
{
"password" : "khm",
"function" : 0,
"id" : 5,
"login" : "khm",
"nom" : "khmayes",
"mail" : "bke#live.fr",
"tel" : "235684522"
}
]
I want to retrieve the names(nom) of users with angular I recovered this list in a variable in my code.
if you do not want to use angular js then you can use simple jquery too.
var list = [{"password":"ppp","function":0,"id":1,"login":"ness","nom":"nesrine","mail":"nes#gmail","tel":"238555555"},{"password":"pass","function":0,"id":2,"login":"bilel.troudi","nom":"bilel","mail":"bilel.troudi91#gmail","tel":null},{"password":"undefined","function":1,"id":4,"login":"undefined","nom":"ahmed","mail":"ahmed#gmail.com","tel":"221474"},{"password":"khm","function":0,"id":5,"login":"khm","nom":"khmayes","mail":"bke#live.fr","tel":"235684522"}];
var nameList = [];
for(var i=0;i<list.length;i++){
nameList.push(list[i].nom);
}
$scope.list =[{"password":"ppp","function":0,"id":1,"login":"ness","nom":"nesrine","mail":"nes#gmail","tel":"238555555"},{"password":"pass","function":0,"id":2,"login":"bilel.troudi","nom":"bilel","mail":"bilel.troudi91#gmail","tel":null},{"password":"undefined","function":1,"id":4,"login":"undefined","nom":"ahmed","mail":"ahmed#gmail.com","tel":"221474"},{"password":"khm","function":0,"id":5,"login":"khm","nom":"khmayes","mail":"bke#live.fr","tel":"235684522"}];
$scope.nameList = [];
angular.forEach($scope.list,function(Obj,val){
$scope.nameList.push(Obj.nom);
});
you can use this code. in $scope.nameList you can get all names.
For this code you have to use angular js
Try
function getNames() {
return $http.get("/allU").then(function(result) {
return result.data.map(function(item) {
return item.nom;
});
});
}
getNames().then(function(data) {
$scope.names = data; //$scope.names = ["nesrine", "bilel", "ahmed", "khmayes"]
})