how to get json response from restapi in angularjs using $resource? - javascript

This is my angularjs code , I am getting response on console put not able to get it in array or json type form
angular.module('user', ['ngResource']).
config(function($httpProvider){
$httpProvider.defaults.headers.common['Accept'] = "application/json"
})
.factory('loginUser', function($resource){
alert("hello amit we done it");
var user=$resource('http://localhost/testtext/index.php/user/login', {}, {
login: {method:'POST'}}
);
console.log(user.login({"user": {"email":"prashant#gmail.com","password":"weldone"}}));
});
console output
Resource {user: Object, $resolved: false, $then: function, $get: function, $save: function…}
$resolved: true
$then: function (b,g){var j=e(),h=
User: Array[1]
0: Object
address: "Noida"
city: "Mathura"
clientid: "clint000000000000009"
country: "India"
email: "prashant#gmail.com"
flag: "0000000000"
fname: "Sushil"
id: "users000000000000041"
lname: "Kumar1"
password: "ee486c2fa50a03b53982cba45ef045c2"
reset_pw_token: ""
session: Object
auth_token: "a1054379e166a085f4f331074c36b6d7"
created_by: null
created_on: null
id: "usaut000000000000187"
scope: "a:11: {i:0;s:19:"user/changepassword";i:1;s:11:"user/logout";i:2;s:12:"role/getrole";i:3;s:17:"ro le/getprivilege";i:4;s:13:"category/save";i:5;s:13:"message/reply";i:6;s:16:"message/classify";i:7;s:12:"message/read";i:8;s:12:"message/list";i:9;s:12:"tag/messages";i:10;s:8:"tag/l ist";}"
updated_by: null
updated_on: "2013-09-03 19:30:52"
user_id: "users000000000000041"
__proto__: Object
state: "UP"
__proto__: Object
length: 1
__proto__: Array[0]
__proto__: Resource

You need to use the success and failure function
user.login({"user": {"email":"prashant#gmail.com","password":"weldone"}},
function(data){
console.log(data[0]) //or data.User[0] or data.user[0] depending upon on your json.
},
function(error) {
console.log(error) // Error details
})

Related

Mongoosejs .find returning whole model instead of document [duplicate]

This question already has answers here:
How do you turn a Mongoose document into a plain object?
(9 answers)
mongoose .find() method returns object with unwanted properties
(5 answers)
How can I display a JavaScript object?
(40 answers)
Model.findOne not returning docs but returning a wrapper object
(1 answer)
Closed 3 years ago.
I am running on .find() query on an existing model. I have used this code in the past and have changed nothing but now all of the sudden it's not working for some reason. I am thinking either MongoDB or MongooseJS updated and the functionality has changed.
var retrieve = function() {
Repo.find({}, function(err, docs) {
console.log(docs)
})
};
retrieve();
returns
[
model {
'$__': InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
version: undefined,
getters: {},
_id: 5e02e91c908f0f086e737189,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: [StateMachine],
pathsToScopes: {},
ownerDocument: undefined,
fullPath: undefined,
emitter: [EventEmitter],
'$options': true
},
isNew: false,
errors: undefined,
_doc: {
__v: 0,
stars: 2,
id: 1322,
url: 'url',
name: 'name',
_id: 5e02e91c908f0f086e737189
},
'$init': true
},
model {
'$__': InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
version: undefined,
getters: {},
_id: 5e02e92c3f6b72088246c563,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: [StateMachine],
pathsToScopes: {},
ownerDocument: undefined,
fullPath: undefined,
emitter: [EventEmitter],
'$options': true
},
isNew: false,
errors: undefined,
_doc: {
__v: 0,
stars: 2,
id: 2,
url: 'url1',
name: 'name1',
_id: 5e02e92c3f6b72088246c563
},
'$init': true
}
]
it should return
[{name: 'name', id: 2, url: 'url', stars: 2},
{name: 'name1', id: 1322, url: 'url1', stars: 2}]
I don't know why this is happening
---- edit for Ahsok ---
I tried using your code
const retrieve = () => {
Repo.find({})
.then(repo => {
console.log({ repo })
})
.catch(error => {
console.log({ error })
})
};
And it's still not returning what it needs to be. Now it's returning
{
repo: [
model {
'$__': [InternalCache],
isNew: false,
errors: undefined,
_doc: [Object],
'$init': true
},
model {
'$__': [InternalCache],
isNew: false,
errors: undefined,
_doc: [Object],
'$init': true
}
]
}
Which is the same thing it was returning above, just in a slightly different format
This is the expected behavior, Mongoose find query always return an instance of a mongoose i.e what you are getting. There are two ways to handle this:
Convert your response to plain Object on your own:
console.log(docs.toObject())
Let mongoose itself do this for you (Using lean):
Repo.find({}).lean().exec(function(err, docs) {
console.log(docs);
});
You can read more about lean here
Hope this helps :)
If you are using async function then use this syntax
const retrieve = async () => {
const repo = await Repo.find({})
console.log(repo)
};
If you have no idea whats going on up there use this syntax
const retrieve = () => {
Repo.find({})
.then(repo => {
console.log({ repo })
})
.catch(error => {
console.log({ error })
})
};
You can take and doc ride from here too.
Why this happens Because find return cursor or promise to retrieve _doc from it you need to use the promise.
Here the first type solution is popular to clean code.
I figured it out. Turned out I had to revert node to a previous version for this to be the default behavior. Using .lean() as Mohammed pointed out would have also worked but I wanted to know why my code was behaving differently than it used to and it turns out that it was caused by a node update.

What internal operation does Mongoose returning object do?

I have a story which may be a little tedious.But I was really confused about this problem.Here it is:
I was trying to change the value of the article object which was returned by Mongoose static Model method in my service layer.Here is what the object looks like:
{
"_id" : ObjectId("5ddc7ce28251373510d4e49b"),
"tag" : [
"Error handling",
"async/await"
],
"title" : "title",
"content" : "This is an article",
"createdAt" : ISODate("2019-11-26T09:16:18.177+08:00"),
"updatedAt" : ISODate("2019-11-26T10:04:41.636+08:00"),
"view" : [
{
"_id" : ObjectId("5ddc7cee8251373510d4e49c"),
"email" : "123",
"viewAt" : ISODate("2019-11-26T09:16:30.733+08:00")
},
{
"_id" : ObjectId("5ddcdcefa4ac2a9f54228a42"),
"email" : "123",
"viewAt" : ISODate("2019-11-26T16:06:07.310+08:00")
},
],
"thumbUp" : [
{
"email" : "123",
"thumbedAt" : ISODate("2019-11-26T16:46:17.870+08:00")
}
],
"comment" : [
{
"_id" : ObjectId("5ddcea9efa1afbbe082cc051"),
"userId" : "5d836cacc845921e1034f1da",
"text" : "fff",
"commentAt" : ISODate("2019-11-26T17:04:30.166+08:00")
},
],
"__v" : 0
},
Then I used userIds inside the comment array to do some other database query(like fetching username) and combined fetched data with the original comment data to form a new comment array. Here what a new comment array looks like:
{
_id: 5ddcea9efa1afbbe082cc051,
userId: '5d836cacc845921e1034f1da',
text: 'This is quite useful!',
commentAt: 2019-11-27T05:59:21.164Z,
username: 'Sherr_Y',
hasAvatar: true
}
Then here comes the problem: When I tried to replace the original comment with the new one.I found nothing changed.Here's what I have tried:
_data.comment = newCommentArray;
// or
Object.assign(_data, { comment: newCommentArray });
Finally I found that _data is not a object which only contains the data.Here's what it really looks like:
{
'$__': InternalCache {
strictMode: true,
selected: {},
shardval: undefined,
saveError: undefined,
validationError: undefined,
adhocPaths: undefined,
removing: undefined,
inserting: undefined,
saving: undefined,
version: undefined,
getters: {},
_id: 5ddc7ce28251373510d4e49b,
populate: undefined,
populated: undefined,
wasPopulated: false,
scope: undefined,
activePaths: StateMachine {
paths: [Object],
states: [Object],
stateNames: [Array]
},
pathsToScopes: {},
cachedRequired: {},
session: undefined,
'$setCalled': Set {},
ownerDocument: undefined,
fullPath: undefined,
emitter: EventEmitter {
_events: [Object: null prototype] {},
_eventsCount: 0,
_maxListeners: 0
},
'$options': { skipId: true, isNew: false, willInit: true }
},
isNew: false,
errors: undefined,
_doc: {
tag: ["Error handling","async/await"],
_id: 5ddc7ce28251373510d4e49b,
title: 'title',
content: 'This is an article',
createdAt: 2019-11-26T01:16:18.177Z,
updatedAt: 2019-11-26T02:04:41.636Z,
view: [
[Object], [Object]
],
thumbUp: [ [Object] ],
comment: [ [Object] ],
__v: 0
},
'$locals': {},
'$init': true
}
Obviously, the value of _doc is just what we exactly need.So I dealt it with const res = Object.assign({ ..._data._doc }, { comment }); Now it works.Even though I can continue my work,I still wonder what magic does the mongoose returning object have.Here I have two main questions:
It only shows the data we need(_doc) when I try below:
console.log(_data);
// Only output what inside _doc
But it output the entire object when I try below:
console.log({ ...data });
// Output the entire object
Why data and { ...data } have different behaviors in console.log.Is it about the javascript internal rules or is it set by Mongoose.And how?
When I use return _data but not return { ..._data } to return it from sevice to controller.I still can get the entire object by console.log({ ...data }) in controller layer.But when I use res.json(_data) to return it to front-end.No matter what I did, I can only get the data inside _doc.Seems like res.json(_data) only returns what inside _doc.But how did this finished?
If you created mongoose query to find something inside your database as an answer you will not receive just an Object it will be a mongoose Query Object which contains a lot of useful staff which you can call on returned mongoose Query Object. Here you can find more about this Query Object and Query Object methods: Monoose Query Object.
To update some properties of your mongoose query object you can use this method:
queryObject.findOneAndUpdate(conditions, update)
I think it will fit perfectly

How to read through [object Object]?

I am reading a list that has the following structure:
export interface ISaleEntity {
id: number;
dateCreated: Date,
amount:number,
type:string,
description:string
}
My api is returning the following data:
payments: Array(2) 0: {Id: 1, Type: "DEBIT", Description: "Sale
1", Amount: 5000, DateCreated: "06/18/2018 00:00:00"} 1: {Id: 2, Type:
"CREDIT", Description: "Sale1", Amount: 4200, DateCreated: "06/20/2018
00:00:00"}
Since I am using transcript, I do
const payments: ISaleEntity [] = response.data.payments;
private renderData(payments: ISaleEntity[]) {
return (
<div>
{payments.length}
{payments.forEach(element =>
// tslint:disable-next-line:no-console
console.log("element" + element)
// <span>{element.description}</span>
)}
</div>
);
}
In console, element is [object Object].
How can I read the loop through JSON object properties?
var elements=[{Id: 1, Type: "DEBIT", Description: "Sale 1", Amount: 5000, DateCreated: "06/18/2018 00:00:00"} ,{Id: 2, Type: "CREDIT", Description: "Sale1", Amount: 4200, DateCreated: "06/20/2018 00:00:00"}]
elements.forEach(function(elem){
console.log(elem);
console.log(elem.Description)
})
console.log(elements[0].Description)
If you want to concatenate with string just use
console.log("element" + JSON.stringify(element)).
+ element coerces the object element into a string, which is just [object Object]
console.log is an overloaded function that accepts a list of parameters that are either passed by copy (string|number|boolean) or by reference (everything else).
Just pass it as another argument to console.log:
console.log("element", element);

MongoError: server localhost:27017 received an error {"name":"MongoError","message":"read ECONNRESET"}

Data to save
{ _id: 56083f1b9a1b20d88c3c3e05,
mayfield: false,
postponed: false,
venue_id: null,
venue: null,
result: [ null ],
league_id: null,
away_id: null,
home_id: null }
{ _id: 56083f1b9a1b20d88c3c3e06,
mayfield: false,
postponed: false,
venue_id: null,
venue: null,
result: [ null ],
league_id: null,
away_id: null,
home_id: null }
Code
var Games = mongoose.model('Games');
var result = new Games();
result.save(function (err, saveData) {
if (err) return console.error(err);
return result;
});
Error thrown
MongoError: server localhost:27017 received an error {"name":"MongoError","message":"read ECONNRESET"}
at null.<anonymous> (c:\var\www\beta.com\node_modules\mongoose\node_modules\mongodb\node_modules\mongodb-core\lib\topologies\server.js:251:47)
at g (events.js:180:16)
at emit (events.js:98:17)
at null.<anonymous> (c:\var\www\beta.com\node_modules\mongoose\node_modules\mongodb\node_modules\mongodb-core\lib\connection\pool.js:77:12)
at g (events.js:180:16)
at emit (events.js:98:17)
at Socket.<anonymous> (c:\var\www\beta.com\node_modules\mongoose\node_modules\mongodb\node_modules\mongodb-core\lib\connection\connection.js:118:49)
at Socket.g (events.js:180:16)
at Socket.emit (events.js:95:17)
at net.js:441:14
at process._tickCallback (node.js:442:13)
{ [MongoError: server localhost:27017 received an error {"name":"MongoError","message":"read ECONNRESET"}]
name: 'MongoError',
message: 'server localhost:27017 received an error {"name":"MongoError","message":"read ECONNRESET"}' }
{ [MongoError: server localhost:27017 received an error {"name":"MongoError","message":"read ECONNRESET"}]
name: 'MongoError',
message: 'server localhost:27017 received an error {"name":"MongoError","message":"read ECONNRESET"}' }
Schema
var GameScheme = new Schema({
fixtureID: String,
date: Date,
home_id: { type: Schema.ObjectId, ref: 'Clubs', default: null },
away_id: { type: Schema.ObjectId, ref: 'Clubs', default: null },
year: String,
season_id: { type: Schema.ObjectId, ref: 'Seasons' },
siteID: String,
leagueID: String,
league_id: { type: Schema.ObjectId, ref: 'Leagues', default: null },
result: {type: Array, default: null},
venue: {type: String, default: null},
venue_id: {type: String, default: null},
postponed: {type: Boolean, default: false},
mayfield: {type: Boolean, default: false}
})
Of course I would like to know how to stop this error, but there isn't enough data for me to understand the real problem.
I have read that it might be the size of the db, however on this particular Model has only 6 rows currently. So I am not sure but it seems unlikely.
...
league_id: null,
away_id: null,
home_id: null },
{ _id: 56083f1b9a1b20d88c3c3e06,
mayfield: false,
postponed: false,
...
Please note the comma (,) after closing brace.
Turns out that the error because I had copied over the following files whilst trying to make a complete backup of the DB:
data
¬ db
¬ mays.0
¬ mays.ns
Once I repaired the db all was good with the world once again.

Backbone model on save only returns form data

In a web application I am building, I save a model via an API - on success I return the model to the console, however the model only contains the data submitted from the form, but yet the API saves various other pieves of data created from the submitted form, how can I get the full model to be return in success callback?
here is my code,
MOdel save,
saveBasicProject: function(e) {
e.preventDefault();
var that = this;
console.log("saving basic project");
var projectData = $('.create-new-project').serializeJSON();
//var projectModel = new app.Project(projectData);
this.model.save(projectData, {
success: function(model, response) {
console.log(model);
that.response_json = JSON.parse(response);
that.collection.add(that.model);
},
error: function(model, response) {
var error_json = response.responseJSON;
$(".create-new-project").before( response.responseJSON.msg );
}
});
},
API save
public function save()
{
$rules = array(
'name' => 'required',
'description' => 'required',
'cost' => 'numeric',
'start_date' => 'required | date',
'end_date' => 'required | date'
);
$validation = Validator::make(Input::all(), $rules);
if($validation->fails()) {
return Response::json( $validation->messages()->first(), 500);
} else {
$project = new Project;
$project->name = Input::get('name');
$project->description = Input::get('description');
$project->total_cost = Input::get('cost');
$project->start_date = Input::get('start_date');
$project->finish_date = Input::get('end_date');
$project->run_number_days = $this->get_days_between_two_dates(Input::get('start_date'), Input::get('end_date'));
$project->num_days_from_year_start = $this->get_days_between_two_dates("2014-01-01", Input::get('start_date'));
$project->color = $this->project_rbg_to_project_hex();
$project->user_id = ResourceServer::getOwnerId();
if( $project->save() ) {
return Response::json($project, 200);
} else {
return Response::json(array( 'error' => 'Something has gone wrong!' ), 500);
}
}
}
What gets returned?
child {cid: "c60", attributes: Object, _changing: false, _previousAttributes: Object, changed: Object…}
_changing: false
_events: Object
_pending: false
_previousAttributes: Object attributes: Object cost: "18000" description: "Description" end_date: "2014/01/30" name: "Simon 18" start_date: "2014/01/01"
__proto__: Object changed: Object cid: "c60" collection: child
__proto__: Surrogate
The POST json
{cost: "23000"
description: "Description"
end_date: "2014/01/30"
name: "Project #23"
start_date: "2014/01/01"}
The response from the server
{
name: "Project#23",
description: "Description",
total_cost: 23000,
start_date: "2014/01/01",
finish_date: "2014/01/30",
run_number_days: 30,
num_days_from_year_start: 1,
color: "#757da3",
user_id: 1,
updated_at: "2014-08-0510: 14: 15",
created_at: "2014-08-0510: 14: 15",
id: 105
}
The above is also getting updated in the DB but the model that gets returned just includes the original request json.
You need to explicitly set the response data to model in success callback.
e.g.
that.model.set(that.response_json);

Categories