Mongoose: Save a JSON with embedded documents, using schemas with references - json

everyone. I tried to save a JSON (RecordNameVersion) like this
{ "created":"2015-11-10 15:47:41.107Z",
"id_user" : "01",
"version" : "1",
"RecordName" : {"status" : "1", "name": "Paul"}
}
In my node application I have this for the schemas
var RecordNameVersion = new Schema({
_id : Number,
created : {type: Date, default: Date.now},
id_user : String,
version : { type: Number, min: 0 },
RecordName : {type: Schema.Types.ObjectId, ref: 'TaxonRecordName'}
});
var RecordName = new Schema({
trn_version : { type: Number, ref: 'RecordNameVersion' },
status : String,
name : String
});
When I try to post the Json, this error is generated.
"message": "RecordNameVersion validation failed",
"name": "ValidationError",
Is possible save all the JSON in one go? or is necessary put embedded the schema for Record Name?
I prefer different collections for RecordNameVersion y RecordName.
Or I should put the id for RecordNameVersion in the json for RecordName

Your error in saving RecordNameVersion is telling you the value of field
RecordName
wants to be a Reference, not some actual object. So synthesize its Reference as :
{
"_id": mongoose.Types.ObjectId("123456789000")
"created":"2015-11-10 15:47:41.107Z",
"id_user" : "01",
"version" : "1",
"RecordName" : mongoose.Types.ObjectId("123456789055")
}
then the corresponding RecordName save could be :
{
"_id": mongoose.Types.ObjectId("123456789055")
"status":"1",
"name" : "Paul",
"version" : "1",
"trn_version" : mongoose.Types.ObjectId("123456789000")
}
Notice the value of _id fields across the two documents

Related

How to retrieve all key-value pairs avoiding key duplication from JSON in Groovy script

I am totally new to groovy script and would like some help to solve this out. I have a JSON response I want to manipulate and get desired parameters back by avoiding duplication. The Json response does not have indexes like 0,1,2.. that I can iterate through.
Here is the response that I want to work with:
{
"AuthenticateV2" : {
"displayName" : "Verification of authentication",
"description" : "notification ",
"smsTemplate" : "authentication.v2.0_sms",
"emailHeaderTemplate" : "v2.0_header",
"emailBodyTemplate" : "html",
"parameters" : {
"displayName" : "USER_DISPLAY_NAME",
"actionTokenURL" : "VERIFICATION_LINK",
"customToken" : "VERIFICATION_CODE"
},
"supportedPlans" : [
"connectGo"
]
},
"PasswordRecovery" : {
"displayName" : "Verification of password recovery",
"description" : "notification",
"smsTemplate" : "recovery.v1.0_sms",
"emailHeaderTemplate" : "recovery.v1.0_header",
"emailBodyTemplate" : "recovery.v1.0_body_html",
"parameters" : {
"displayName" : "USER_DISPLAY_NAME",
"actionTokenURL" : "VERIFICATION_LINK",
"customToken" : "VERIFICATION_CODE",
"adminInitiated" : false,
"authnId" : "AUTHENTICATION_IDENTIFIER",
"authnType" : "EMAIL",
"user" : {
"displayName" : "USER_DISPLAY_NAME"
}
},
"supportedPlans" : [
"connectGo"
]
},
"PasswordReset" : {
"displayName" : "password reset",
"description" : "notification",
"smsTemplate" : "recovery.v1.0_sms",
"emailHeaderTemplate" : "recovery.v1.0_header",
"emailBodyTemplate" : "html",
"parameters" : {
"displayName" : "USER_DISPLAY_NAME",
"user" : {
"displayName" : "USER_DISPLAY_NAME"
}
}
The expected output that I want to have:
{
"displayName" : "USER_DISPLAY_NAME",
"actionTokenURL" : "VERIFICATION_LINK",
"customToken" : "VERIFICATION_CODE",
"customToken" : "VERIFICATION_CODE",
"adminInitiated" : false,
"authnId" : "AUTHENTICATION_IDENTIFIER",
"authnType" : "EMAIL"
}
I need to retrieve all fields under parameters tag and also want to avoid duplication
You should first get familiar with parsing and producing JSON in Groovy.
Then, assuming the provided response is a valid JSON (it's not - there are 2 closing curlies (}) missing at the end) to get all the parameters keys merged into one JSON we have to convert the JSON string into a Map object first using JsonSlurper:
def validJsonResponse = '<your valid JSON string>'
Map parsedResponse = new JsonSlurper().parseText(validJsonResponse) as Map
Now, when we have a parsedResponse map we can iterate over all the root items in the response and transform them into the desired form (which is all the unique parameters keys) using Map::collectEntries method:
Map uniqueParameters = parsedResponse.collectEntries { it.value['parameters'] }
Finally, we can convert the uniqueParameters result back into a pretty printed JSON string using JsonOuput:
println JsonOutput.prettyPrint(JsonOutput.toJson(uniqueParameters))
After applying all the above we'll get the output
{
"displayName": "USER_DISPLAY_NAME",
"actionTokenURL": "VERIFICATION_LINK",
"customToken": "VERIFICATION_CODE",
"adminInitiated": false,
"authnId": "AUTHENTICATION_IDENTIFIER",
"authnType": "EMAIL",
"user": {
"displayName": "USER_DISPLAY_NAME"
}
}
If you want to get rid of user entry from the final output just remove it from the resulting uniqueParameters map (uniqueParameters.remove('user')) before converting it back to JSON string.

minLength not working with String in JSON Schema

I am pretty new to node, so might be the case I am using the JSON Schema not correctly, please correct me if I am wrong.
I have been using the npm module named jsonschema.
And for using validation I am using it like:
var Validator = require('jsonschema').Validator;
var v = new Validator();
var instance = {
"user_id" : "jesus",
"password" : "password"
};
var schema = {
"id" : "Login_login",
"type" : "object",
"additionalProperties" : false,
"properties" : {
"user_id": {
"type" : "string",
"required": true,
"minLenth" : 8,
"maxLength" : 10,
"description": "User id to login."
},
"password" : {
"type" : "string",
"required": true,
"minLength" : 8,
"maxLength" : 10,
"description" : "password to login."
}
}
};
var result = v.validate(instance, schema);
console.log('>>>>>> ' + result);
But the point is result is not having an error although the the minLength of user_id is kept as 8 but I have passed 5 characters, so if I am not wrong result should throw an error for the same, Why is it so
:(
The schema itself needs validation. Its "user_id" condition "minLength" spelled without a "g".

mongo db remove json objects

I have a mongo json object as follows
{
"_id" : new BinData(3, "RDHABb22XESWvP83FplqJw=="),
"name" : "NEW NODE",
"host" : null,
"aet" : null,
"studies" : ["1.3.12.2.1107.5.99.3.30000008061114424970500000589"],
"testcases" : [new BinData(3, "Zhl+zIXomkqAd8NIkRiTjQ==")],
"sendentries" : [{
"_id" : "1.3.12.2.1107.5.99.3.30000008061114424970500000589",
"Index" : 0,
"Type" : "Study"
}, {
"_id" : "cc7e1966-e885-4a9a-8077-c3489118938d",
"Index" : 1,
"Type" : "TestCase"
}]
}
The fields "Studies" and "TestCases" are now obsolete and I am now storing that information in a new field called SendEntries. I would like to get rid of the Studies and TestCases from the old entries and unmap those fields going forward. I want to know how I can update my current collections to get rid of the Studies and TestCases fields.
I'm just few weeks into Mongo.
You can use the $unset operator with update.
db.collection.update({},
{ $unset: {
"studies": "",
"testcases": ""
},
{ "upsert": false, "muti": true }
)
And that will remove all of the fields from all of your documents in your collection
Use $unset, there's a manual page e.g.
db.yourCollection.update( { },
{ $unset: {
Studies: "",
testcases: ""
}
},
{ multi: true }
)

Define Backbone model for content-type "application/x-www-form-urlencoded"

I am having some issues in assigning the data to the model.
Data is coming is in the foll format.
"Address" : [{
"id" : "1"
"name" : "abc"
"phone" : "9876543210",
"email" : "abc#example.com"
},{
"id" : "2"
"name" : "XYZ"
"phone" : "9872543210",
"email" : "XYZ#example.com"
}]
But the model i have created for above looks like the foll :
var AddressBookModel= Backbone.Model.extend({
defaults: {
name: "",
phone: "",
email: ""
},
idAttribute: "id"
});
I Know this is not the correct model created for the data.
What is the correct way to define the model for above format?
If your are looking to "parse away" the Address object and return an array in your collection try this parse method:
var c = Backbone.Collection.extend({
parse: function(data){
return data.Address;
}
});

Sencha Touch nested JSON - Store load with Associations

I want to load nested JSON in a Store, but the data is not correctly mapped. No problem with a single regModel but I canĀ“t get the associations to work.
// JSON in test.json
{"message" : {
"returnCodes": [
{
"value": "0",
"code": "200",
"description": "OK"
},
{
"value": "0",
"code": "200",
"description": "OK"
}
]
}}
// Model with associations
Ext.regModel("ReturnCode", {
fields : [{
name : "value",
type : "string"
}, {
name : "code",
type : "string"
}, {
name : "description",
type : "string"
}],
belongsTo: "Message"
});
Ext.regModel("Message", {
hasMany: {
model : "ReturnCode",
name : "returnCodes"
}
});
// Store
var jobStore = new Ext.data.Store({
model : 'Message',
autoLoad: true,
proxy : {
type : 'ajax',
url: 'test.json',
reader : {
type : 'json',
root : 'message.returnCodes'
}
}});
// List
var list = Ext.extend( Ext.List, {
fullscreen : true,
store : jobStore,
grouped : false,
itemTpl : '<div>{code}</div>' // no output
});
When I look into the store every data is stored in the raw section of the store object but nothing in the data section. In the list for both returnCode Objects a listitem is created but they are not filled with data, because the mapping didn't succeed -> itemTpl gets no data.
Try declaring Message Model first, then add associationKey:'returnCodes' in hasMany{} within the Message Model. Also change the root of the reader to message.
This reference could also be of use to you.