posting objectId in postman - json

I'm trying to post this json to an API using postman
{
"order" : [{ "mealId": 562b2649b2e70464f113c04d, "quantity": 4}],
"service_id" : 562b2649b2e70464f113c04d,
"dest" : "Allabama",
"active": false
}
but I keep getting this error
SyntaxError: Unexpected token b
at Object.parse (native)
at parse (C:\nodeprojects\foodDelivery\node_modules\body-parser\lib\types\json.js:88:17)
at C:\nodeprojects\foodDelivery\node_modules\body-parser\lib\read.js:108:18
at invokeCallback (C:\nodeprojects\foodDelivery\node_modules\body-parser\node_modules\raw-body\index.js:262:16)
at done (C:\nodeprojects\foodDelivery\node_modules\body-parser\node_modules\raw-body\index.js:251:7)
at IncomingMessage.onEnd (C:\nodeprojects\foodDelivery\node_modules\body-parser\node_modules\raw-body\index.js:308:7)
at IncomingMessage.emit (events.js:104:17)
at _stream_readable.js:908:16
at process._tickCallback (node.js:355:11)
its a nodejs api with mongoose.
This is the schema for the json object
var mongoose = require('mongoose');
var OrdersSchema = new mongoose.Schema({
order : [{ mealId: mongoose.Schema.Types.ObjectId, quantity: Number}],
service_id : mongoose.Schema.Types.ObjectId,
dest : String,
orderTime : {type:Date, default:Date.now},
completeTime : {type:Date, default:Date.now},
active: Boolean,
});
So in short the problem is when I try to pass the ObjectId, It stops reading after the "562" and sees the 'b' as an illegal character.

You must quote the strings:
{
"order" : [{ "mealId": "562b2649b2e70464f113c04d", "quantity": 4}],
"service_id" : "562b2649b2e70464f113c04d",
"dest" : "Allabama",
"active": false
}

receive the _id object as a string and not as ObjectId,
when you got this id create new mongo.driver ObjectId
public async Task<IHttpActionResult> PostExample(string idinstring)
{
ObjectId d=new ObjectId(idinstring);
}

Related

Admin SDK Chromeosdevices method

I'm using Google Scripts to maintain a list of Chrome devices on our domain.
I'm using the AdminDirectory.Chromeosdevices.list method to get all the information I require and write it to a sheet.
I am then trying to write a script to write information to the annotatedLocation and annotatedAssetId fields using the Chromeosdevices.update method.
My problem: I receive a phrase error using the following, from looking at the suggestion: update(resource, customerId, deviceId, optionalArgs) I don't seem to have a 'resource', I cannot seem to find any way to get this value.
Any suggestions as to how I can get the resource??
var options = {
"annotatedAssetId": (data[i][13] == "") ? data[i][3] : data[i][13],
"annotatedLocation": (data[i][14] == "") ? data[i][4] : data[i][14],
"notes": (data[i][15] == "") ? data[i][7] : data[i][15],
"orgUnitPath": (data[i][16] == "") ? data[i][15] : data[i][16]
}
var device = AdminDirectory.Chromeosdevices.update(data[i][11],"my_customer", data[i][10], options)
Thank you
I think you're referring to this line:
In the request body, supply a Chromeosdevices resource with the
following properties:
resource is referring to Chromeosdevices resource.
{
"kind": "admin#directory#chromeosdevice",
"etag": etag,
"deviceId": string,
"serialNumber": string,
"status": string,
"lastSync": datetime,
"supportEndDate": datetime,
"annotatedUser": string,
"annotatedLocation": string,
"annotatedAssetId": string,
"notes": string,
"model": string,
"meid": string,
"orderNumber": string,
"willAutoRenew": boolean,
"osVersion": string,
"platformVersion": string,
"firmwareVersion": string,
"macAddress": string,
"bootMode": string,
"lastEnrollmentTime": datetime,
"orgUnitPath": string,
"recentUsers": [
{
"type": string,
"email": string
}
],
"ethernetMacAddress": string,
"activeTimeRanges": [
{
"date": date,
"activeTime": integer
}
]
}
Click the link for more info.
This is working for me. Hopefully it helps you out.
function getDeviceID(assetID) {
//Find chrome device
var assetTag = 'asset_id:' + assetID;
var chromebookDevices = (AdminDirectory.Chromeosdevices.list("my_customer", {
query: assetTag
}));
//Change values
chromebookDevices.chromeosdevices[0].annotatedUser = 'New name';
//Push changes
var updatedChromebook =(AdminDirectory.Chromeosdevices.update(chromebookDevices.chromeosdevices[0], "my_customer", chromebookDevices.chromeosdevices[0].deviceId));
}
Maybe this has been figured out already, but the first argument is the JSON object noogui refers to. Use the method on adminDirectory.Chromeosdevices.get() to first retrieve the object. Modify this object as needed, then use adminDirectory.Chromeosdevices.update() with that modified object as the first argument.

How to convert a MongoDB document to JSON Object

I am trying to make a post request with the MongoDB document returned from find query, as the request body in NodeJS.But on the server I'm getting the Error : Invalid JSON. Below is the document that I'm trying to POST
{
"_id" : ObjectId("5739a6bf3f1b41477570dc89"),
"taskCount" : 2,
"study" : "cod",
"phase" : "mansa2",
"rhimeTaskId" : "5739a6bec4567f6e737fd3db",
"recordId" : "5726f3cfc4567f6e737fc3ab",
"recordStudy" : "codstudy",
"recordPhase" : "mansa2",
"recordLanguage" : "Punjabi",
"recordScript" : "Latin",
"_state" : "CodingComplete",
"tasks" : [
{
"physician" : ObjectId("5739a6bd3f1b41477570dc78"),
"stage" : "Coding",
"result" : {
"cod" : "C15",
"feedback" : {
"narrativeLength" : "Adequate",
"positiveSymptomsIncluded" : "Only Positive",
"certainty" : "High"
},
"keywords" : [
"52 yr male, died of food pipe cancer, suffered pain upper abdomen, investigated,FNAC confirmed Cancer, Put on Chemotherapy, multiple cycles, died at home, had fever with chills occasionally"
]
}
},
{
"physician" : ObjectId("5739a6bd3f1b41477570dc79"),
"stage" : "Coding",
"result" : {
"cod" : "C15",
"feedback" : {
"narrativeLength" : "Inadequate",
"positiveSymptomsIncluded" : "Only Positive",
"certainty" : "High"
},
"keywords" : [
"severe pain abdomen, ultrasonography revealed food pipe cancer, chemotherapy given, died"
]
}
}
],
"__v" : 2
}
and here is the code that I wrote to make the POST request
var MongoClient = require('mongodb').MongoClient;
var request = require('request');
var assert = require('assert');
var cmeprovisioning= 'mongodb://localhost:27017/cmeprovisioning';
MongoClient.connect(cmeprovisioning, function(err, db) {
assert.equal(null, err);
var count=0;
console.log("Connected to cmeprovisioning");
var cursor =db.collection('rhimeReport').find(
{"study":"cod","phase":"mansa2","recordStudy":"codstudy",
"recordPhase":"mansa2","_state":"CodingComplete"
});
cursor.each(function(err, doc) {
assert.equal(err, null);
if (doc != null) {
console.dir(doc);
count=count+1;
request({url: "http://cme.host.net:8081/cme-provisioning/update",
method: "POST",json: true,
headers: {"content-type": "application/json"},
json: doc
},function(e,r,b){
console.log("POST Error "+count+" "+e)
console.log("POST Response "+count+" "+r)
console.log("POST BODY "+count+" "+b)
});
} else {
console.log("Some Error : "+err)
}
});
});
I also tried using JSON.stringify(doc), but still got the Invalid JSON error. Is there a way I can use mongo document returned by the find query and convert it to JSON to make the POST request.
I think those ObjectID is what making it an invalid JSON document.
Here's the actual answer:
If you want to convert a mongo object to JSON object.
There's a utility method in every mongo object toJSON
So you can simply do mongoResponseObject.toJSON() on the response object.
e.g.
Products.findById(id).then(res => {
const jsonRes = res.toJSON();
// Here jsonRes is JSON
})
Alternatively you can directly get the JSON object by using the .lean() like this.
Products.findById(id).lean().then(res => {
// Here res is JSON
})
you need to convert object id to string ie.
var result = {
"_id": ObjectId("5739a6bf3f1b41477570dc89"),
"taskCount": 2,
"study": "cod"
};
//now convert to string
result=result._id.toString();
//now you can use the result
Try this,
var cursor =db.collection('rhimeReport').find(
{"study":"cod","phase":"mansa2","recordStudy":"codstudy",
"recordPhase":"mansa2","_state":"CodingComplete"});
cursor.toString();
......
Hope this help.
Try this in robomongo
var cursor = db.getCollection('X').find({},{})
while(cursor.hasNext()) {
print(JSON.stringify(cursor.next()))
}

Ember-Data: embedded objects in JSON data is lost

I have a model called ticket-stats, defined as follows:
import Model from 'ember-data/model';
import attr from 'ember-data/attr';
export default Model.extend({
opened24Hours: attr('number'),
miRelated: attr('number'),
autoClosed24Hours: attr('number'),
inQueue: attr('number'),
activeGreater48: attr('number'),
behindNct: attr('number'),
manuallyClosed24Hours: attr('number'),
handoff: attr('number')
});
The data for this comes from a service which yields the following JSON:
{
"get_tickets": {
"behind_nct": {
"inequality": null,
"stat_name": "Behind NCT",
"value": 0,
"update_time": "2016-05-26 18:05:11",
"threshold": null
},
...
}
}
I have a custom serializer for this model:
import JSONSerializer from 'ember-data/serializers/json';
export default JSONSerializer.extend({
normalizeResponse(store, primaryModelClass, payload, id, requestType) {
console.log(payload);
var data = {};
data.id = 1;
data.opened24Hours = payload.get_tickets.tickets_opened_last_24_hours.value;
data.miRelated = payload.get_tickets.mi_related_tickets.value;
data.autoClosed24Hours = payload.get_tickets.tickets_closed_goliath_last_24_hour.value;
data.inQueue = payload.get_tickets.tickets_in_queue.value;
data.activeGreater48 = payload.get_tickets.active_greater_48.value;
data.behindNct = payload.get_tickets.behind_nct.value;
data.manuallyClosed24Hours = payload.get_tickets.tickets_closed_last_24_hours.value;
data.handoff = payload.get_tickets.handoff_tickets.value;
return this._super(store, primaryModelClass, data, id, requestType);
}
});
The values for the attributes of my model are all null. When i look at the payload on the console, I see that the innermost objects (i.e. behind_nct) don't contain the correct attributes:
behind_nct: Object
__proto__: Object
__defineGetter__ : __defineGetter__()
__defineSetter__ : __defineSetter__()
__lookupGetter__ : __lookupGetter__()
__lookupSetter__ : __lookupSetter__()
constructor : Object()
hasOwnProperty : hasOwnProperty()
isPrototypeOf : isPrototypeOf()
propertyIsEnumerable : propertyIsEnumerable()
toLocaleString : toLocaleString()
toString : toString()
valueOf : valueOf()
get __proto__ : get __proto__()
set __proto__ : set __proto__()
Is there something wrong with the JSON api or with my configuration of the Ember model? Or both?
When i go to the URL for the json, everything seems fine. I can see all the data.
You need to form a correct JSON API payload from your server's response:
let ticks= payload.get_tickets;
let data= {
ticket_stats: [{
opened24Hours: ticks.tickets_opened_last_24_hours.value,
// etc. etc.
}]
};
You need to identify the model type ticket_stats in the payload.

Mongoose .populate() only showing 1 document

I am trying to output just the hometeam name's to the page so that I can try to understand how to work with my code better. It is only printing one team to the page, and it is printing all the details of that team to the page, whereas I only want it to print one part.
This is my code, I want it to print the name's of each hometeam to the page
app.get('/home', function(req, res) {
Match.findOne({}).populate('hometeam.name').exec(function(err, teams){
util.log(teams);
res.send(teams);
});
});
But when I load the page all I get is the first piece of data from this list of Matches
[
{
"hometeam": "5106e7ef9afe3a430e000007",
"_id": "5113b7ca71ec596125000005",
"__v": 0,
"key": 1360246730427
},
{
"hometeam": "5113c13e0eea687b28000001",
"_id": "5113e951354fe70330000001",
"__v": 0,
"key": 1360259409361
},
{
"hometeam": "5113c13e0eea687b28000001",
"_id": "5113e999354fe70330000002",
"__v": 0,
"key": 1360259481412
}
]
Also, if I try to put util.log(teams.hometeam.name) I get the following:
TypeError: Cannot call method 'toString' of undefined
But I would want it to be able to print the name which belongs to hometeam here. As hometeam is just the objectId of a Team in my database, am I missing something with the DBreferencing here?
Update:
Team Schema
var Team = new Schema({
'key' : {
unique : true,
type : Number,
default: getId
},
'name' : { type : String,
validate : [validatePresenceOf, 'Team name is required'],
index : { unique : true }
}
});
module.exports.Schema = Team;
module.exports.Model = mongoose.model('Team', Team);
Match Schema
var Team = require('../schemas/Team').Schema;
var Match = new Schema({
'key' : {
unique: true,
type: Number,
default: getId
},
'hometeam' : { type: Schema.ObjectId, ref: 'Team' },
'awayteam' : { type: Schema.ObjectId, ref: 'Team' }
});
module.exports = mongoose.model('Match', Match);
Populate takes the property name of the property you are trying to retrieve. This means that you should use 'hometeam' instead of 'hometeam.name'. However, you want to retrieve the name of the team so you could filter for that. The call would then become..
Match.findOne({}).populate('hometeam', {name: 1}).exec(function(err, teams)
Now you have a property called 'hometeam' with in that the name. Have fun :)
EDIT
Showing how to have a single mongoose instance in more files to have correct registration of schemas.
app.js
var mongoose = require('mongoose');
var Team = require('./schemas/team-schema')(mongoose);
var Match = require('./schemas/match-schema')(mongoose);
// You can only require them like this ONCE, afterwards FETCH them.
var Team = mongoose.model('Team'); // LIKE THIS
schemas/match-schema.js
module.exports = function(mongoose) {
var Match = new mongoose.Schema({
'key' : {
unique: true,
type: Number,
default: getId
},
'hometeam' : { type: mongoose.Schema.ObjectId, ref: 'Team' },
'awayteam' : { type: mongoose.Schema.ObjectId, ref: 'Team' }
});
return mongoose.model('Match', Match);
};
schemas/team-schema.js
module.exports = function(mongoose) {
var Team = new mongoose.Schema({
'key' : {
unique : true,
type : Number,
default: getId
},
'name' : { type : String,
validate : [validatePresenceOf, 'Team name is required'],
index : { unique : true }
}
});
return mongoose.model('Team', Team);
};

EXT Js Complex JSON Response Handling : Grid Insertion

Hello I am trying to insert a JSON record into the grid dynamically.
My server response is as below :
{
"studentDetails":{
"status":"ACTIVE",
"subject":"MATH",
"paymentOptions":"EFT",
"idStudent":71,
"firstName":"Alli",
"lastName":"Alli",
"middleName":"Alli",
"grade":"A",
"kumonLevel":"FK",
"parentId":68,
"userId":1,
"parentBean":{
"parentFirstName":"Alli",
"idParent":68,
"parentMiddleName":"Alli",
"parentLastName":"Alli",
"parentEmailId":"haigopi#gmail.com",
"parentPhoneNumber":"3173797945"},
"startTimeSlot":"12:00 AM",
"endTimeSlot":"12:15 AM",
"dob":"2012-07-04"},
"success":true
}
A student having parentDetails as a seperate object in the above response.
at my client I did the following :
i had a grid with the below configuration :
var studentRecord = Ext.data.Record.create( [ {
name : 'firstName',
type : 'string'
}, {
name : 'lastName',
type : 'string'
}, {
name : 'middleName',
type : 'string'
}, {
name : 'grade',
type : 'string'
}, {
name : 'kumonLevel',
type : 'string'
}, {
name : 'startTimeSlot',
type : 'string'
}, {
name : 'endTimeSlot',
type : 'string'
}, {
name : 'subject',
type : 'string'
}, {
name : 'dob',
type : 'date'
}, {
name : 'status',
type : 'string'
}, {
name : 'paymentOptions',
type : 'string'
}, {
name : 'parentFirstName',
mapping : 'parentBean.parentFirstName',
type : 'string'
}, {
name : 'parentLastName',
mapping : "parentBean['parentLastName']",
type : 'string'
}, {
name : 'parentMiddleName',
mapping : 'parentBean.parentMiddleName',
type : 'string'
}, {
name : 'parentPhoneNumber',
mapping : 'parentBean.parentPhoneNumber',
type : 'String'
}, {
name : 'parentEmailId',
mapping : 'parentBean.parentEmailId',
type : 'string'
} ]);
var myProxy = new Ext.data.HttpProxy( {
method : 'GET',
url : 'listActiveStudents.do'
});
var studentsListReader = new Ext.data.JsonReader( {
successProperty : 'success',
root : 'studentDetails',
idProperty : 'idStudent'
}, studentRecord);
var studentDS = new Ext.data.Store( {
proxy : myProxy,
autoLoad : true,
totalProperty : 'total',
reader : studentsListReader
});
upon data receiving from the server I did the following :
handler : function() {
studentForm.getForm().submit({
url : 'createStudent.do',
waitMsg : 'Saving Data...',
submitEmptyText : false,
success : function(form, action) {
win.close();
var studentDetail = action.result.studentDetails;
var xyz = new studentDS.recordType(studentDetail, 0);
studentDS.insert(0,xyz);
}
});
}
The problem what I am facing here is :
When the record is inserted the parentDetails are not showing up in the grid. Seems, the mapping is not working properly while inserting. Where as while loading the grid initially it renders perfectly. I created the record well which shows in firefox debbuger with valid values too.
could any one guide me please?
This is a very tricky issue. but I found an easy (but dirty) solution, which you just need to edit the line where you create your record, from this:
var xyz = new studentDS.recordType(studentDetail, 0);
to this:
var xyz = new studentDS.recordType(
studentDS.reader.extractValues(
studentDetail,
studentDS.fields.items,
studentDS.fields.length
), studentDetail.idStudent); //use the idStudent of the studentDetail, so the id of the newly created record equals to your idStudent
And here is why
So after tracing the calling stack, I found an interesting differences between the records you loaded from Store, and the record that you created through your new studentDS.recordType.
Look at the differences:
//This is the record created from Store Load event
dob: Wed Jul 04 2012 00:00:00 GMT+0800 (Malay Peninsula Standard Time)
endTimeSlot: "12:15 AM"
firstName: "Alli"
grade: "A"
kumonLevel: "FK"
lastName: "Alli"
middleName: "Alli"
parentEmailId: "haigopi#gmail.com"
parentFirstName: "Alli"
parentLastName: "Alli"
parentMiddleName: "Alli"
parentPhoneNumber: "3173797945"
paymentOptions: "EFT"
startTimeSlot: "12:00 AM"
status: "ACTIVE"
subject: "MATH"
__proto__: Object
//This is the record created from your studentDS.recordType
dob: "2012-07-04"
endTimeSlot: "12:15 AM"
firstName: "Alli"
grade: "A"
idStudent: 80
kumonLevel: "FK"
lastName: "Alli"
middleName: "Alli"
parentBean: Object
idParent: 68
parentEmailId: "haigopi#gmail.com"
parentFirstName: "Alli"
parentLastName: "Alli"
parentMiddleName: "Alli"
parentPhoneNumber: "3173797945"
__proto__: Object
parentId: 68
paymentOptions: "EFT"
startTimeSlot: "12:00 AM"
status: "ACTIVE"
subject: "MATH"
userId: 1
__proto__: Object
In fact, while you load your data, your JsonStore and JsonReader did a dirty hack to your loaded data. They linearize your data. They move all your data from your parentBean to the root of the record.data, so while rendering the grid, your grid can be rendered correctly.
To know how they render your grid, check the code at Line 827 of GridView.js
meta.value = column.renderer.call(column.scope, record.data[column.name], meta, record, rowIndex, i, store);
Notice how the GridView is capturing the values. They use record.data[column.name] to get the value of each fields, and this is where all your parent* report undefined.
And so to know how they linearize your codes, you can check line 157 of DataReader.js
var record = new Record(this.extractValues(n, fi, fl), this.getId(n));
//where:
//n = your raw json object
//fi = the field items
//fl = the field length
And in fact the new Record they used here is identical with your new studentDS.recordType, with the exception that they extractValues for you on behalf, and clearly you did not do it because it's not obvious to do so.
Got it? Hope the explanation is clear enough.