Merge pull request #409 from alingavriliuc/main

✨ improved MongoDB cheatsheet layout, added EJS cheatsheet
This commit is contained in:
Fechin authored and GitHub committed 2023-04-11 09:30:06 +08:00
commit 769e25ea80
2 files changed
+274 -51

No files matched your search

+232
View File
@@ -0,0 +1,232 @@
---
title: EJS
date: 2023-04-07
background: bg-[#b4ca65]
tags:
- EJS
- Frontend
- Framework
categories:
- Programming
intro: What is the "E" for? "Embedded?" Could be. How about "Effective," "Elegant," or just "Easy"? EJS is a simple templating language that lets you generate HTML markup with plain JavaScript. No religiousness about how to organize things. No reinvention of iteration and control-flow. It's just plain JavaScript.
plugins:
- copyCode
---
## Get Started { .cols-2 }
### Install
```
npm install ejs
```
### Use
Pass EJS a template string and some data. BOOM, you've got some HTML.
```
let ejs = require('ejs');
let people = ['geddy', 'neil', 'alex'];
let html = ejs.render('<%= people.join(", "); %>', {people: people});
```
### CLI
Feed it a template file and a data file, and specify an output file.
```
ejs ./template_file.ejs -f data_file.json -o ./output.html
```
### Browser Support
Download a browser build from the latest release, and use it in a script tag.
```
<script src="ejs.js"></script>
<script>
let people = ['geddy', 'neil', 'alex'];
let html = ejs.render('<%= people.join(", "); %>', {people: people});
</script>
```
## Docs
### Example
```
<% if (user) { %>
<h2><%= user.name %></h2>
<% } %>
```
### Usage
```
let template = ejs.compile(str, options);
template(data);
// => Rendered HTML string
ejs.render(str, data, options);
// => Rendered HTML string
ejs.renderFile(filename, data, options, function(err, str){
// str => Rendered HTML string
});
```
### Includes
```
<ul>
<% users.forEach(function(user){ %>
<%- include('user/show', {user: user}); %>
<% }); %>
</ul>
```
### Custom delimiters
```
let ejs = require('ejs'),
users = ['geddy', 'neil', 'alex'];
// Just one template
ejs.render('<?= users.join(" | "); ?>', {users: users},
{delimiter: '?'});
// => 'geddy | neil | alex'
// Or globally
ejs.delimiter = '$';
ejs.render('<$= users.join(" | "); $>', {users: users});
// => 'geddy | neil | alex'
```
### Caching
```
let ejs = require('ejs'),
LRU = require('lru-cache');
ejs.cache = LRU(100); // LRU cache with 100-item limit
```
### Custom file loader
```
let ejs = require('ejs');
let myFileLoader = function (filePath) {
return 'myFileLoader: ' + fs.readFileSync(filePath);
};
ejs.fileLoader = myFileLoader;
```
### Layouts
```
<%- include('header'); -%>
<h1>
Title
</h1>
<p>
My page
</p>
<%- include('footer'); -%>
```
## Client-side support { .cols-1 }
### Example
```
<div id="output"></div>
<script src="ejs.min.js"></script>
<script>
let people = ['geddy', 'neil', 'alex'],
html = ejs.render('<%= people.join(", "); %>', {people: people});
// With jQuery:
$('#output').html(html);
// Vanilla JS:
document.getElementById('output').innerHTML = html;
</script>
```
### Caveats
```
let str = "Hello <%= include('file', {person: 'John'}); %>",
fn = ejs.compile(str, {client: true});
fn(data, null, function(path, d){ // include callback
// path -> 'file'
// d -> {person: 'John'}
// Put your code here
// Return the contents of file as a string
}); // returns rendered string
```
## Options { .cols-1 }
### Options list
| Option | Description |
|-------------------|------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
| cache | Compiled functions are cached, requires filename |
| filename | Used by cache to key caches, and for includes |
| root | Set project root for includes with an absolute path (e.g., /file.ejs). Can be an array to try to resolve include from multiple directories. |
| views | An array of paths to use when resolving includes with relative paths. |
| context | Function execution context |
| compileDebug | When false, no debug instrumentation is compiled |
| client | Returns standalone compiled function |
| delimiter | Character to use for inner delimiter, by default '%' |
| openDelimiter | Character to use for opening delimiter, by default '<' |
| closeDelimiter | Character to use for closing delimiter, by default '>' |
| debug | Outputs generated function body |
| strict | When set to `true`, generated function is in strict mode |
| _with | Whether or not to use with() {} constructs. If false, then the locals will be stored in the locals object. (Implies `--strict`) |
| localsName | Name to use for the object storing local variables when not using with Defaults to locals |
| rmWhitespace | Remove all safe-to-remove whitespace, including leading and trailing whitespace. It also enables a safer version of -%> line slurping for all scriptlet tags (it does not strip new lines of tags in the middle of a line). |
| escape | The escaping function used with <%= construct. It is used in rendering and is .toString()ed in the generation of client functions. (By default escapes XML). |
| outputFunctionName| Set to a string (e.g., 'echo' or 'print') for a function to print output inside scriptlet tags. |
| async | When true, EJS will use an async function for rendering. (Depends on async/await support in the JS runtime. |
## Tags { .cols-1 }
### Tags list
| Tag | Description |
|------|----------------------------------------------------------------------|
| <% | 'Scriptlet' tag, for control-flow, no output |
| <%_ | 'Whitespace Slurping' Scriptlet tag, strips all whitespace before it |
| <%= | Outputs the value into the template (HTML escaped) |
| <%- | Outputs the unescaped value into the template |
| <%# | Comment tag, no execution, no output |
| <%% | Outputs a literal '<%' |
| %> | Plain ending tag |
| -%> | Trim-mode ('newline slurp') tag, trims following newline |
| _%> | 'Whitespace Slurping' ending tag, removes all whitespace after it |
## Cli { .cols-1 }
### Cli list
| Option | Description |
|----------------|-------------------------------------------------------------------------------------------------------------------------|
| cache | Compiled functions are cached, requires filename |
| -o / --output-file FILE | Write the rendered output to FILE rather than stdout. |
| -f / --data-file FILE | Must be JSON-formatted. Use parsed input from FILE as data for rendering. |
| -i / --data-input STRING | Must be JSON-formatted and URI-encoded. Use parsed input from STRING as data for rendering. |
| -m / --delimiter CHARACTER | Use CHARACTER with angle brackets for open/close (defaults to %). |
| -p / --open-delimiter CHARACTER | Use CHARACTER instead of left angle bracket to open. |
| -c / --close-delimiter CHARACTER| Use CHARACTER instead of right angle bracket to close. |
| -s / --strict | When set to `true`, generated function is in strict mode |
| -n / --no-with | Use 'locals' object for vars rather than using `with` (implies --strict). |
| -l / --locals-name | Name to use for the object storing local variables when not using `with`. |
| -w / --rm-whitespace | Remove all safe-to-remove whitespace, including leading and trailing whitespace. |
| -d / --debug | Outputs generated function body |
| -h / --help | Display this help message. |
| -V/v / --version | Display the EJS version. |
Examples of use :
```
$ ejs -p [ -c ] ./template_file.ejs -o ./output.html
$ ejs ./test/fixtures/user.ejs name=Lerxst
$ ejs -n -l _ ./some_template.ejs -f ./data_file.json
```
+42 -51
View File
@@ -63,9 +63,8 @@ load("myScript.js")
## Crud
### Create & Delete
### Create
#### Create
```mongosh
db.coll.insertOne({name: "Max"})
db.coll.insert([{name: "Max"}, {name:"Alex"}]) // ordered bulk insert
@@ -74,7 +73,7 @@ db.coll.insert({date: ISODate()})
db.coll.insert({name: "Max"}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
```
#### Delete
### Delete
```mongosh
db.coll.remove({name: "Max"})
@@ -99,7 +98,7 @@ db.coll.update({"_id": 1}, {$currentDate: {"lastModified": true}})
db.coll.update({"_id": 1}, {$currentDate: {"lastModified": {$type: "timestamp"}}})
```
#### Array
### Array { .row-span-2 }
```mongosh
db.coll.update({"_id": 1}, {$push :{"array": 1}})
@@ -114,46 +113,44 @@ db.coll.updateMany({}, {$inc: {"grades.$[]": 10}})
db.coll.update({}, {$set: {"grades.$[element]": 100}}, {multi: true, arrayFilters: [{"element": {$gte: 100}}]})
```
#### Update many
### Update many { .row-span-1 }
```mongosh
db.coll.update({"year": 1999}, {$set: {"decade": "90's"}}, {"multi":true})
db.coll.updateMany({"year": 1999}, {$set: {"decade": "90's"}})
```
#### FindOneAndUpdate
### FindOneAndUpdate { .row-span-1 }
```mongosh
db.coll.findOneAndUpdate({"name": "Max"}, {$inc: {"points": 5}}, {returnNewDocument: true})
```
#### Upsert
### Upsert { .row-span-1 }
```mongosh
db.coll.update({"_id": 1}, {$set: {item: "apple"}, $setOnInsert: {defaultQty: 100}}, {upsert: true})
```
#### Replace
### Replace { .row-span-1 }
```mongosh
db.coll.replaceOne({"name": "Max"}, {"firstname": "Maxime", "surname": "Beugnet"})
```
#### Save
### Save { .row-span-1 }
```mongosh
db.coll.save({"item": "book", "qty": 40})
```
#### Write concern
### Write concern { .row-span-1 }
```mongosh
db.coll.update({}, {$set: {"x": 1}}, {"writeConcern": {"w": "majority", "wtimeout": 5000}})
```
### Read {.row-span-3}
#### Find
### Find { .row-span-2 }
```mongosh
db.coll.findOne() // returns a single document
@@ -165,7 +162,7 @@ db.coll.find({name: "Max", age: 32}).explain("executionStats") // or "queryPlann
db.coll.distinct("name")
```
#### Count
### Count
```mongosh
db.coll.count({age: 32}) // estimation based on collection metadata
@@ -173,7 +170,7 @@ db.coll.estimatedDocumentCount() // estimation based on collection metadata
db.coll.countDocuments({age: 32}) // alias for an aggregation pipeline - accurate count
```
#### Comparison
### Comparison
```mongosh
db.coll.find({"year": {$gt: 1970}})
@@ -185,7 +182,7 @@ db.coll.find({"year": {$in: [1958, 1959]}})
db.coll.find({"year": {$nin: [1958, 1959]}})
```
#### Logical
### Logical
```mongosh
db.coll.find({name:{$not: {$eq: "Max"}}})
@@ -199,7 +196,7 @@ $and: [
})
```
#### Element
### Element
```mongosh
db.coll.find({name: {$exists: true}})
@@ -207,7 +204,7 @@ db.coll.find({"zipCode": {$type: 2 }})
db.coll.find({"zipCode": {$type: "string"}})
```
#### Aggregation Pipeline
### Aggregation Pipeline
```mongosh
db.coll.aggregate([
@@ -217,20 +214,20 @@ db.coll.aggregate([
])
```
#### Text search with a "text" index
### Text search with a "text" index
```mongosh
db.coll.find({$text: {$search: "cake"}}, {score: {$meta: "textScore"}}).sort({score: {$meta: "textScore"}})
```
#### Regex
### Regex
```mongosh
db.coll.find({name: /^Max/}) // regex: starts by letter "M"
db.coll.find({name: /^Max$/i}) // regex case insensitive
```
#### Array
### Array
```mongosh
db.coll.find({tags: {$all: ["Realm", "Charts"]}})
@@ -238,7 +235,7 @@ db.coll.find({field: {$size: 2}}) // impossible to index - prefer storing the si
db.coll.find({results: {$elemMatch: {product: "xyz", score: {$gte: 8}}}})
```
#### Projections
### Projections
```mongosh
db.coll.find({"x": 1}, {"actors": 1}) // actors + \_id
@@ -246,32 +243,29 @@ db.coll.find({"x": 1}, {"actors": 1, "\_id": 0}) // actors
db.coll.find({"x": 1}, {"actors": 0, "summary": 0}) // all but "actors" and "summary"
```
#### Sort, skip, limit
### Sort, skip, limit
```mongosh
db.coll.find({}).sort({"year": 1, "rating": -1}).skip(10).limit(3)
```
#### Read Concern
### Read Concern
```mongosh
db.coll.find().readConcern("majority")
```
---
## Databases and Collections
## Databases and Collections { .cols-2 }
### Drop
### Drop { .row-span-1 }
```mongosh
db.coll.drop() // removes the collection and its index definitions
db.dropDatabase() // double check that you are *NOT* on the PROD cluster... :-)
```
### Create Collection
Create collection with a $jsonschema
### Create Collection { .row-span-2}
```mongosh
db.createCollection("contacts", {
@@ -297,7 +291,7 @@ db.createCollection("contacts", {
})
```
### Other Collection Functions
### Other Collection Functions { .row-span-1}
```mongosh
db.coll.stats()
@@ -308,17 +302,18 @@ db.coll.validate({full: true})
db.coll.renameCollection("new_coll", true) // 2nd parameter to drop the target collection if exists
```
---
## Indexes {.cols-2}
### Basics
#### List
```mongosh
db.coll.getIndexes()
db.coll.getIndexKeys()
```
#### Drop Indexes
```mongosh
@@ -353,12 +348,9 @@ db.coll.createIndex({"name": 1}, {collation: {locale: 'en', strength: 1}}) //
db.coll.createIndex({"name": 1 }, {sparse: true})
```
## Others { .cols-2 }
## Others
### Handy commands
### Handy commands { .row-span-3 }
```mongosh
use admin
@@ -401,19 +393,7 @@ db.getFreeMonitoringStatus()
db.createView("viewName", "sourceColl", [{$project:{department: 1}}])
```
### Change Streams
```mongosh
watchCursor = db.coll.watch( [ { $match : {"operationType" : "insert" } } ] )
while (!watchCursor.isExhausted()){
if (watchCursor.hasNext()){
print(tojson(watchCursor.next()));
}
}
```
### Replica Set
### Replica Set { .row-span-2}
```mongosh
rs.status()
@@ -435,7 +415,7 @@ rs.slaveOk()
rs.stepDown(20, 5) // (stepDownSecs, secondaryCatchUpPeriodSecs)
```
### Sharded Cluster
### Sharded Cluster { .row-span-2 }
```mongosh
sh.status()
@@ -465,3 +445,14 @@ sh.addShardToZone("shard0000", "JFK")
sh.removeShardFromZone("shard0000", "NYC")
sh.removeRangeFromZone("mydb.coll", {a: 1, b: 1}, {a: 10, b: 10})
```
### Change Streams {.row-span-1 }
```mongosh
watchCursor = db.coll.watch( [ { $match : {"operationType" : "insert" } } ] )
while (!watchCursor.isExhausted()){
if (watchCursor.hasNext()){
print(tojson(watchCursor.next()));
}
}
```