As the title describes, I am trying to find out if I can instantiate a new mongoose model and schema with the JSON of a existing MongoDB document? It seems like I could do it as long as I have retrieve the document before Mongoose runs.
Is this possible? Ideally I would like to do it on the fly where I do NOT need to restart node.
**** Edit ****** Here is what I have tried.
note: the setTimeout is in there incase the schema creation is async. This is a down and dirty mockup just to see if this concept works. :).
THIS Does NOT Work!!!
function initModels(models) {
for (var i = 0, l = models.length; i < l; i++) {
console.log(models[i])
exports[models[i].name + "Schema"] = mongoose.Schema(models[i].model, {collection: "ModelData"});
(function(itrModel){
var model = itrModel;
setTimeout(function(){
exports[model.name] = mongoose.model(model.name.toUpperCase(), model.name + "Schema");
},2000)
})(models[i])
}
}
exports.getModels = function () {
DataConnection.Connect(function (db) {
var collectionName = "Models";
var collection = db.collection(collectionName);
collection.find().toArray(function (err, models) {
initModels(models);
})
})
};
Here is the model that is stored in the db
{
"name" : {
"type" : "String",
"required" : true
},
"email" : {
"type" : "String",
"required" : false,
"index" : true,
"index" : true
},
"password" : {
"type" : "String",
"required" : true
},
"role" : {
"type" : "String",
"required" : true
},
"createDate" : {
"type" : "Number",
"required" : true
}
}
Related
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
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
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".
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 }
)
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.