is there a quick method to return saved data to its default value in mongoose.js - node.js

In my User Schema I have various fields with various default values. By example, see a few fields below:
acceptedStatus: {
type: String,
trim: true,
default: 'no' //possibilities (no, yes, thinkingAboutIt, yesInFuture)
}
Is there a way to quickly return the saved data for a particular field to its default value without explicitly doing it like
user.acceptedStatus = 'no';
and, if so, is there a way to return all fields that carry default values to their original status. Thanks for your help. There are times when I need to quickly do this, and didn't know if there were any methods I am missing.

One way could be that you store schema in an object, then from that object you can easily come to know what property have defaults.

Related

PDFTron: What is the proper way to find date fields in a PDF form

[PdfTron 5.2]
I have a PDF form with text and date fields. I want to find the date fields.
I can get the actions of the field with getActions().
field.getActions()
returns
{"F":[{"yc":"JavaScript","Gt":"AFDate_FormatEx(\"dd.mm.yyyy\");"}],
"K":[{"yc":"JavaScript","Gt":"...);","ey":null}]}
As you can see, the date is in actions.F[0].Gt. But checking actions.F[0].Gt
for "AFDate" seems wrong, that's too low-level.
Is there a better API function to find out, that I have a date field?
Thank you.
You are correct. The Gt property is obfuscated and minified which is volatile and not meant to be used. If you require an API, you should refer to our documentation. Everything should be available there except a few (one of which will be used below), but feel free to contact us if you do need help!
Unfortunately, there is no API currently to get that type. From my limited understanding, the "type" of a field is determined by the attached actions and not simply a specific type or flag. This suggests all fields are just text fields with special formatting actions to make it look and feel like its a date or numeric field.
In this case, you will have to check the formatting action (F) as you have already noticed for the date formatting function (AFDate_FormatEx). To get the JavaScript from that action, you should use the javascript property on the action which was not in the documentation. However, you can see it if you console log the action.
Here is an example:
const dateActionJs = /.+:"AFDate_FormatEx\(.*/;
instance.docViewer.on('annotationsLoaded', () => {
const annotations = annotManager.getAnnotationsList();
annotations.forEach(annot => {
const actions = annot.getField().getActions();
if (actions.F && actions.F[0] && actions.F[0].javascript && dateActionJs.test(actions.F[0].javascript)) { // F = Format Action
console.log('Found Date');
}
});
});
Let me know if this helps!
EDIT: You can search for AFDate instead of AFDate_FormatEx which will be sufficient.

Why am I unable to change values of a Mongoose object to a different type ‘directly’?

I've just spent a good hour figuring out something mind-boggling (at least to me, as a JS noob) and I'd like to understand the underlying logic (or just why it works this way, because I think it's illogical and quite unexpected).
Suppose I'm using Mongoose to retrieve documents from a database, some or all of which include a date property (created with new Date()), a numeric property, and a string property.
[{
string: 'foo',
date: '2018-10-13T21:11:39.244Z',
number: 10
},
...
{
string: 'bar',
date: '2018-10-13T21:12:39.244Z',
number: 20
}]
I thus obtain an array of objects and now want to take the date property for each object and change the value to a string, so I do something like:
doc.find({}, (err, list) => {
list.forEach((item, index) => {
list[index].date = 'new value'
})
})
But I can't do that!
I can do list[index].string = 'new value' as well as list[index].date = new Date() but I can't change values that are of a different type, in this example date and number.
However, when I do list[index]._doc.date = 'new value', which took so long to figure out because I didn't know Mongoose objects weren't just plain old objects and focused on solving problems I didn't have instead, I can modify the value just fine.
It appears that the mongoose object somehow translates obj.key to obj._doc.key only if the type of the value matches but I'd appreciate a more detailed explanation than my uneducated guesses.
I suppose you want to use multi type on a document field, Mongoose support this by "Mixed" type when you define the Schema.
You can get more detail from https://mongoosejs.com/docs/schematypes.html#mixed.

How do you set the value of 'DocumentShowInSiteMap' property in Kentico?

How do you set the value of DocumentShowInSiteMap property in Kentico?
I've tried:
Using the DocumentHelper and TreeHelper apis but with both, this property doesn't give you access to the setter.
Tried running a SQL Query setting the value of dbo.CMS_Document.DocumentShowInSiteMap to 1 and 0. These queries run fine but when I go to the pages app, there is no change in the 'Show in sitemap' property checkbox, ie. setting the database field to 0 doesn't 'untick' this checkbox.
I'm trying to run a scheduled task which will set this property for documents at a specified location automatically. What is the proper way to do this? Any help appreciated.
Have you tried this?
int TheDocumentToModify = 1221;
var PageItem = DocumentHelper.GetDocument(TheDocumentToModify , new TreeProvider());
foreach(var culturePage in PageItem.CultureVersions)
{
culturePage.SetValue("DocumentShowInSiteMap", true);
// May need to apply Workflow check in / check out, see Kentico API examples based on your need.
culturePage.Update();
}
Within code, there is no simple way. Setter should be available within special class DocumentCultureDataInfo and it should be saved with SetObject. This class contains all of culture DB fields and is manipulated by DocumentCultureDataInfoProvider.
This class is an internal property of TreeNode. However I have not tried doing this arbitrary in code and mentioned classes are part of innner API.
Your second approach should work, but documents and their properties are cached and you will need to refresh cache so that new DB value is actually picked up Loading of this property goes through simple GetData in LoadDefaultValues for each TreeNode.
Trevor J Fayas's answer would probably work. I figured this out yesterday and just leaving my solution here just in case:
TreeHelper
.GetDocuments(task.CurrentSiteName, aliaspath, null, false, "", "", "", -1, false, -1)
.Where(doc => doc.DocumentShowInSiteMap)
.ToList()
.ForEach(node =>
{
node.SetValue("DocumentShowInSiteMap", false);
node.Update();
});
Obviously replace aliaspath with the one you need or use DocumentHelper.GetDocuments which takes different parameters.

What is the meaning `required` in mongoose Schema?

I am writing a mongoose schema, and I would like to understand the properties of the same.
Here is my schema:
var UserSchema = new Schema({
name: String,
username: { type: String, required: true, index: { unique: true }},
password: { type: String, required: true, select: false }
});
Why required is not declared for `name' - ?
Why required declared?
What is select - true/false -means?
When the index - should declared any why?
Why required is not declared for `name' - ?
Answer: When a field is mandatory to fill then in that case we mention it as required. So here "name" is not required or mandatory field.
Why `required' declared?
Answer: As mentioned above, When a field is mandatory to be filled then in that case we mention it as required.
What is select - true/false -means?
Answer: This means that it will not be returned by default in the data when you fetch the document. you can specify if this path should be included or excluded from query results by default.
Schema options
When the index - should declared any why?
Answer: Index should be declared when you are searching data on that field frequently so when you create indexing on that field in that case it do not search that field in all the collections it will search value for that field using index and will return result very quickly.
How indexes work in mongodb
Here, these act as model for your project. So, required is used as validation and index is working as index over that field
Now you have two ways :
either put validation over here in schemas/models
or just manually create validation for form at frontend using JS/Jquery and then long route
Now your answers:
Name is not compulsory to be filled in. That's why no required is put over there.
when there is mandatory to fill any value for that field. Then required is used in schemas.
True/False enables or disables the usage of validation over that field. If you are using false means filling in for that field isn't compulsion at all. But using false is considered a good practice.
Index is special data structure which are used for increasing performance during read/search operations. It increases the speed of operations and are stored in memory.
whenever we have to validate the particular field, so we used required.
required: true means you must fill that field.
required: false means you may or may not fill that field, but its a good practice.

Mongodb. How to get boolean value representing existance of id in an array of ids?

I've got a model which have property
_idUserReadArr // array of users who have read an article
It is going to be a huge array.
And I want my API to return a boolean value
isRead
Which should be true if _idUserReadArr contains particular id and false in other case.
So, instead of
_idUserArr = [1, 2, 3]
I want to get isRead = true or isRead = false and do NOT return or do some manipulations directly with big _idUserReadArr array.
I'n working with node.js using mongoose.
Without using the aggregation framework, you can't change the nature of the output, but with a simple wrapper, you can come very close. In this case, using the aggregation framework really isn't necessary as this solution is simple and efficient.
When you specify the find that you need, just limit the results to a single field (like _id).
http://mongoosejs.com/docs/api.html#model_Model.find
myModel.find({ ... condition ... }, "_id", function(err, docs) {
// the existence of the doc means your condition was true
// without sending back the entire document/array structure
});
findOne also has the same functionality (as do several of the other findXYZ functions in Mongoose).
This functionality is supported by MongoDB's native support for a projection as documented here.

Resources