How to compare API request JSON with existing json document in MongoDb? - json

The title of the question is self explanatory. I want to know what differences are there in JSON Document A which comes from API request and JSON Document B which is already in Mongo DB.how to get changes column name and data also.. i am creating log..that's why i want...
Below is the code of what I'm trying:
NodeJS APICode//
function Updatejob(req, res) {
return function (jobSchedule) {
var obj = new Date();
CompareJSON(req, mongodbjson);
return Job.create(req.body).then(.....)
}
Already Data in Mongodb before Update Record
{
"_id" : ObjectId("586d1032aef194155028e9c7"),
"history" : [
{
"_id" : ObjectId("586d1032aef194155028e9c4"),
"updated_by" : "",
"details" : "Job Created",
"changetype" : "Created",
"datetime" : ISODate("2017-01-04T15:09:38.465Z")
}
],
"current_status" : "Pending",
"time" : 0
}
//REQUEST FOR UPDATE DATA
{
"_id" : ObjectId("586d1032aef194155028e9c7"),
"history" : [
{
"_id" : ObjectId("586d1032aef194155028e9c4"),
"updated_by" : "",
"details" : "Job Completed",
"changetype" : "Completed",
"datetime" : ISODate("2017-01-04T15:09:38.465Z")
}
],
"current_status" : "Completed",
"time" : 0
}

You can use jsondiffpatch:
var delta = jsondiffpatch.diff(object1, object2);
See:
https://www.npmjs.com/package/jsondiffpatch

Related

blocked user Json Query for mongodb

I have three Post in my collection of three different User
I am trying to fetch the post in my Views Session (Html, Css) Part
But I need to filter the other two post Posted from other two User
because I have some block functionality in my View Section. So all post are
allowed but the user I have blocked her/his post not visible to me and mine to him.
BlockedByUser : (This is my Post Json Data)
{
"_id" : ObjectId("591729b52bb30a19afc9b89d"),
"createdTime" : ISODate("2017-05-13T15:43:49.381Z"),
"isDeleted" : false,
"Message" : "Message Two",
"postedBy" : ObjectId("598adbefb3bf0b85f92edc3b"),
"recipient" : [
ObjectId("598ae453b3bf0b85f92ee331"),
ObjectId("5910691ae2bcdeab80e875f0")
],
"updatedTime" : ISODate("2017-05-20T09:24:39.124Z")
}
Below two user Post Data that I have blocked And
In his recipient Array Key stores my Id recipient [598adbefb3bf0b85f92edc3b]
Block User One :
{
"_id" : ObjectId("591729b52bb30a19afc9b89d"),
"createdTime" : ISODate("2017-05-13T15:43:49.381Z"),
"isDeleted" : false,
"Message" : "Message One",
"postedBy" : ObjectId("598ae453b3bf0b85f92ee331"),
"recipient" : [
ObjectId("598adbefb3bf0b85f92edc3b"),
ObjectId("5910691ae2bcdeab80e875f0"),
ObjectId("598ac93cb3bf0b85f92ece44"),
],
"updatedTime" : ISODate("2017-05-20T09:24:39.124Z")
}
Same as above
Block User Two :
{
"_id" : ObjectId("591729b52bb30a19afc9b89d"),
"createdTime" : ISODate("2017-05-13T15:43:49.381Z"),
"isDeleted" : false,
"Message" : "Message One",
"postedBy" : ObjectId("598ac93cb3bf0b85f92ece44"),
"recipient" : [
ObjectId("598adbefb3bf0b85f92edc3b"),
ObjectId("5910691ae2bcdeab80e875f0"),
ObjectId("598ae453b3bf0b85f92ee331")
],
"updatedTime" : ISODate("2017-05-20T09:24:39.124Z")
}
This is Block Collection that I have created and two blocked user Id with blockUserId key
Block Details One :
{
"_id" : ObjectId("598da2f0b88b0c2b0c735234"),
"blockUserId" : ObjectId("598ae453b3bf0b85f92ee331"),
"blockById" : ObjectId("598adbefb3bf0b85f92edc3b"),
"updatedDate" : ISODate("2017-08-11T12:28:32.145Z"),
"createdDate" : ISODate("2017-08-11T12:28:32.145Z"),
"isBlock" : "true",
"__v" : 0
Block Details Two
{
"_id" : ObjectId("598da558b88b0c2b0c735236"),
"blockUserId" : ObjectId("598ac93cb3bf0b85f92ece44"),
"blockById" : ObjectId("598adbefb3bf0b85f92edc3b"),
"updatedDate" : ISODate("2017-08-11T12:38:48.772Z"),
"createdDate" : ISODate("2017-08-11T12:38:48.772Z"),
"isBlock" : "true",
"__v" : 0
}
I have fetch these blocked collection and store two user blockUserId id in array
arrOne = ["598ae453b3bf0b85f92ee331", "598ac93cb3bf0b85f92ece44"]
And i am applying this query in mongoose db:
query = {$or: [{$and: [{ $or: [{ postedBy: req.params.id},
{recipient: req.params.id}
]
}, { createdTime: { $gt: endTime, $lt: startTime } }
]},{postedBy: {$ne: arrOne}}
]
};
}
But it will return undefined value
I am trying to fetch only my Post or Other user Post that not Blocked my Me, And Blocked User Post will not visible to me
I have to Implement where clause and it works
var query = { $and: [{ $or: [{ postedBy: req.params.id }, { recipient: req.params.id }] }, { "createdTime": { $gt: endTime, "$lt": startTime } }] };
CollectionName.find(query).where('postedBy').nin(blocklist).exec(function(err, response);

Nodejs per client mongoose schema

So I want to offer my users the ability to upload CSV and from that generate a mongoose schema, that I store in the DB against that user. When the user logs in, they can create a collection according to their personal schema. Using generate-schema I am able to create a json schema which looks like:
{
"_id" : ObjectId("596a872cd1e59c6135fa7b2e"),
"title" : "Product Set",
"type" : "array",
"items" : {
"type" : "object",
"properties" : {
"booktitle" : {
"type" : "string"
},
"bookid" : {
"type" : "string"
},
"bookauthor" : {
"type" : "string"
}
},
"required" : [
"booktitle",
"bookid",
"bookauthor"
],
"title" : "Product"
},
"$schema" : "http://json-schema.org/draft-04/schema#"
}
and store that in my schema collection. All good...
When I want to create a collection according to that schema, and store data in it using mongoose, I have tried to retrieve the schema from the database (which works) and then do
var generatedSchema = GenerateSchema.mongoose(response)
I then create a model from that with:
var Model = db.models.Product || db.model('Product', generatedSchema);
and create an item from that model
var item = new Model({
"_id": new ObjectID(),
booktitle: 'The Godfather',
bookid: 'abc123',
bookauthor: 'Mario Puzo'
});
and save it:
item.save(function(err, response) { ... })
I don't get any errors but when I save it, in the collection I just see:
{
"_id" : ObjectId("5970b1a584d396d7a2241eba"),
"items" : {
"required" : []
},
"__v" : 0
}
Can anyone point me in the right direction as to why this isn't working? My suspicion is I am using the wrong type of schema to create the model.
If someone has an answer to the above, how would you then go about creating methods on the schema, as you would if the schema was static and part of the codebase of the application?
Thanks

Update same field in multiple documents with data from json

I have a MongoDB looking like this:
[
{
"status" : 0,
"name" : "Yaknow",
"email" : "yaknow#not.this",
"_id" : "5875a42ea469f40c684de385"
},
{
"status" : 1,
"name" : "johnk",
"email" : "johnk#not#this",
"_id" : "586e31c6ce07af6f891f80fd"
}
]
Meanwhile, all the emails have changed and I got a Json with the new ones:
[
{
"email" : "yaknow#gmai.new",
"_id" : "5875a42ea469f40c684de385"
},
{
"email" : "johnk#gmail.new",
"_id" : "586e31c6ce07af6f891f80fd"
}
]
How do I update all the emails?
There is no operator in mongodb which allows you modify string value by replacing some part of string. You should get documents, and then for each of documents you should locally prepare updated value and update document:
db.collection.find({}).forEach(function(doc){
var newEmail = doc.email.substr(0, doc.email.indexOf('#')) + "#gmail.new";
db.collection.update({_id: doc._id}, {$set:{email: newEmail}});
});

How do I loop over JSON without keyname in Angular2?

Here is my code snippet: I know I am getting a result from my webservice because it is returning a 200 ok.
but I cannot loop through to pull the data elements out.
this.cityService.searchByRegion(formData)
.subscribe((resultsReturned) => {
console.log("ResultsReturned :" + resultsReturned);
resultsReturned.forEach((city) => {
var newSearchResult = new SearchResult(city);
this.results.push(newSearchResult);
});
Here is the JSON returned:
[ {
"region_id" : "8",
"time" : "2015-01-16T08:31:40",
"bus_count" : "200",
"speed" : "15.68",
"number_of_reads" : "3412"
}
, {
"region_id" : "8",
"time" : "2015-01-15T08:31:39",
"bus_count" : "200",
"speed" : "15.68",
"number_of_reads" : "3535"
}
, {
"region_id" : "8",
"time" : "2015-01-14T08:40:47",
"bus_count" : "200",
"speed" : "14.32",
"number_of_reads" : "3463"
}]
How do I return my JSON data parsed out, using the forEach?
I tried returnResults.json ... but that just returned a buth of object:object
I am pretty new to Angular2, so any help would be appreciated.

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 }
)