I'm trying to create a show function which needs to access to two documents: The document in 'doc' reference and another document called 'users'
My function looks like:
function(doc,req){
var friends = doc.friends;
var listFriends = [];
for(int i = 0; i<friends.length; i++){
var phone = friends[i].phone;
if(users[phone] != "" ){
listFriends.push(users[phone]);
}
}
return JSON.stringify(listFriends);
}
I'm not an expert nor javascript neither couchdb. My question is, Is it possible to access to the second document (users) in a similar way like in the code? So far it returns a compilation error.
Thanks
You can only access one document in a CouchDB show function. You could look at using a list function, which works on view results instead of documents.
Create a view where the two documents collate together (appear side-by-side in the view order) and you achieve an effect pretty close to what you wanted to achieve with the show function.
Related
I have been searching for hours, but I cannot find anything about this.
Situation:
Backend, existing of NodeJS + Express + Mongoose (+ MongoDB ofcourse).
Frontend retrieves object from the Backend.
Frontend makes some changes (adds/updates/removes some attributes).
Now I use mongoose: PersonModel.findByIdAndUpdate(id, updatedPersonObject);
Result: added properties are added. Updated properties are updated. Removed properties... are still there!
Now I've been searching for an elegant way to solve this, but the best I could come up with is something like:
var properties = Object.keys(PersonModel.schema.paths);
for (var i = 0, len = properties.length; i < len; i++) {
// explicitly remove values that are not in the update
var property = properties[i];
if (typeof(updatedPersonObject[property]) === 'undefined') {
// Mongoose does not like it if I remove the _id property
if (property !== '_id') {
oldPersonDocument[property] = undefined;
}
}
}
oldPersonDocument.save(function() {
PersonModel.findByIdAndUpdate(id, updatedPersonObject);
});
(I did not even include trivial code to fetch the old document).
I have to write this for every Object I want to update. I find it hard to believe that this is the best way to handle this. Any suggestions anyone?
Edit:
Another workaround I found: to unset a value in MongoDB you have to set it to undefined.
If I set this value in the frontend, it is lost in the REST-call. So I set it to null in the frontend, and then in the backend I convert all null-values to undefined.
Still ugly though. There must be a better way.
You could use replaceOne() if you want to know how many documents matched your filter condition and how many were changed (I believe it only changes one document, so this may not be useful to know). Docs: https://mongoosejs.com/docs/api/model.html#model_Model.replaceOne
Or you could use findOneAndReplace if you want to see the document. I don't know if it is the old doc or the new doc that is passed to the callback; the docs say Finds a matching document, replaces it with the provided doc, and passes the returned doc to the callback., but you could test that on your own. Docs: https://mongoosejs.com/docs/api.html#model_Model.findOneAndReplace
So, instead of:
PersonModel.findByIdAndUpdate(id, updatedPersonObject);, you could do:
PersonModel.replaceOne({ _id: id }, updatedPersonObject);
As long as you have all the properties you want on the object you will use to replace the old doc, you should be good to go.
Also really struggling with this but I don't think your solution is too bad. Our setup is frontend -> update function backend -> sanitize users input -> save in db. For the sanitization part, we use a helper function where we integrate your approach.
private static patchModel(dbDocToUpdate: IModel, dataFromUser: Record<string, any>): IModel {
const sanitized = {};
const properties = Object.keys(PersonModel.schema.paths);
for (const key of properties) {
if (key in dbDocToUpdate) {
sanitized[key] = data[key];
}
}
Object.assign(dbDocToUpdate, sanitized);
return dbDocToUpdate;
}
That works smoothly and sets the values to undefined. Hence, they get removed from the document in the db.
The only problem that remains for us is that we wanted to allow partial updates. With that solution that's not possible and you always have to send everything to the backend.
EDIT
Another workaround we found is setting the property to an empty string in the frontend. Mongo then also removes the property in the database
I am importing products from a product feed. A product has a designer and a category and I made them separate tables (Parse classes).
The problem now is that I need to check if a category or designer already exists so I don't need to create it.
Currently I am not checking it, causing many duplicates in my DB. If I checked in DB, it would be asynchronous but I actually need it to be somehow sequential(serialized).. Any ideas?
for (var i=1;i<productsFromFeed.length;i++){
productId = parseInt(productsFromFeed[i][1]);
if (productId > lastProduct.get("productId")){
console.log("Product is new: " + productId);
var Designer = Parse.Object.extend("Designer");
var Product = Parse.Object.extend("Product");
var Category = Parse.Object.extend("Category");
var designer = new Designer();
designer.set("name", productsFromFeed[i][4]);
designer.set("designerId", parseInt(productsFromFeed[i][5]));
var category = new Category();
category.set("name", productsFromFeed[i][6]);
category.set("categoryId", parseInt(productsFromFeed[i][7]));
var newProduct = new Product();
newProduct.set("productName", productsFromFeed[i][0]);
newProduct.set("productId", parseInt(productsFromFeed[i][1]));
newProduct.set("designer", designer);
newProduct.set("category", category);
objects.push(newProduct);
} else {
console.log("Product already exists: " + productId);
}
}
It doesn't need to be serial, you just need to deal with the asynchronous nature of what you're trying to do - using promises.
You could run a query to find everything in advance and locally cache them, that's only useful if you're doing a bulk import, your code does look like a small bulk import but it isn't clear if this will be an efficient approach.
In your case just run your queries and use promises to chain each logical stage together. Note that for your loop you can put the resulting promises into an array and wait till they're all complete.
I am new to jscript and have problems to get all elements in a subgrid.
I tried the code from this sites,
Retrieve rows in crm2011 subgrid with JScript
https://lakshmanindian.wordpress.com/2012/05/25/retrieve-subgrid-rows-in-crm-2011-using-jscript/
but get every time the error message:
(Translated)
Error in the user defined event of the field
Field:window
Event: onload
Error: The preference "control" of a undefined or null reference can not be called.
The last code I tried:
var grid = document.getElementById("accountContactsGrid").control;
for (var rowNo = 0; rowNo<grid.getRecordsFromInnerGrid().length; rowNo++)
for (var cellNo = 0; cellNo<grid.getRecordsFromInnerGrid()[rowNo][3].cells.length; cellNo++)
alert(grid.getRecordsFromInnerGrid()[rowNo][3].cells[cellNo].outerText);
I tried it in the entity Account(Company) with the subgrid "accountContactsGrid".
My main goal would be to catch all the assigned elements in the account form and list it under the contacts form. But only if the checkbox "Eko" is activated.
This is my working code so far:
var chkEko = Xrm.Page.getAttribute("testcrm_ekonomi").getValue();
if (chkEko === true)
{
alert("Eko active: " + chkEko);
}
else
{
alert("Eko not active: " + chkEko);
}
After a time and the help of some threads I was able to get information of this grid. But now I have the problem to catch the elements.
I looked up the variable "grid" and found out that variable is an Object.
Since I don't really know the properties of the objects I tried to get it all.
But it seems, that my code doesn't work and I can not understand why.
Here is the code so far:
function subgridItemCount() {
// Get the Subgrid Control
var grid = Xrm.Page.ui.controls.get('accountContactsGrid')._control;
var keys = Object.keys(grid);
var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
for(var i = 0; i<keys.length; i++) {
document.write(keys[i]);
}
}
First I wanted to get the property of the object and then the propertyValue.
Or is there an other way to get all values of an object?
It seems like I am on the wrong way. This is what I try to do:
In the account/company form is an existing grid which is called Contacts. In this field are some Contacts assigned (with the button "add existing contact").
Now when I open some Contact there should be a box/grid/iframe with a list of all companies this contact is assigned too.
This list should be linked to the Companies (When i click on them CRM should open the form).
Maybe someone can give me a tip?
My plan was first to look for all companies and then to compare the assigned contacts to the opened one with some Jscript. Then the script should list all matching contacts in the contact form.
This way is not really performant since the script needs to read all companies first. But I don't know an other way...
I'm using mongodb to store application error logs as json documents. I want to be able to format the error logs as HTML rather than returning the plain json to the browser. The logs are properly schemaless - they could change at any time, so it's no use trying to do this (in Jade):
- var items = jsonResults
- each item in items
h3 Server alias: #{item.ServerAlias}
p UUID: #{item.UUID}
p Stack trace: #{item.StackTrace}
h3 Session: #{item.Session}
p URL token: #{item.Session.UrlToken}
p Session messages: #{item.Session.SessionMessages}
as I don't know what's actually going to be in the JSON structure ahead of time. What I want is surely possible, though? Everything I'm reading says that the schema isn't enforced by the database but that your view code will outline your schema anyway - but we've got hundreds of possible fields that could be removed or added at any time so managing the views in this way is fairly unmanageable.
What am I missing? Am I making the wrong assumptions about the technology? Going at this the wrong way?
Edited with extra info following comments:
The json docs look something like this
{
"ServerAlias":"GBIZ-WEB",
"Session":{
"urltoken":"CFID=10989&CFTOKEN=f07fe950-53926E3B-F33A-093D-3FCEFB&jsessionid=84303d29a229d1",
"captcha":{
},
"sessionmessages":{
},
"sessionid":"84197a667053f63433672873j377e7d379101"
},
"UUID":"53934LBB-DB8F-79T6-C03937JD84HB864A338",
"Template":"\/home\/vagrant\/dev\/websites\/g-bis\/code\/webroot\/page\/home\/home.cfm, line 3",
"Error":{
"GeneratedContent":"",
"Mailto":"",
"RootCause":{
"Message":"Unknown tag: cfincflude.",
"tagName":"cfincflude",
"TagContext":[
{
"RAW_TRACE":"\tat cfhome2ecfm1296628853.runPage(\/home\/vagrant\/dev\/websites\/nig-bis\/code\/webroot\/page\/home\/home.cfm:3)",
"ID":"CFINCLUDE",
"TEMPLATE":"\/home\/vagrant\/dev\/websites\/nig-bis\/code\/webroot\/page\/home\/home.cfm",
"LINE":3,
"TYPE":"CFML",
"COLUMN":0
},
{
"RAW_TRACE":"\tat cfdisplay2ecfm1093821753.runPage(\/home\/vagrant\/dev\/websites\/nig-bis\/code\/webroot\/page\/display.cfm:6)",
"ID":"CFINCLUDE",
"TEMPLATE":"\/home\/vagrant\/dev\/websites\/nig-bis\/code\/webroot\/page\/display.cfm",
"LINE":6,
"TYPE":"CFML",
"COLUMN":0
}
]
}
}
... etc, but is likely to change depending on what the individual project that generates the log is configured to trigger.
What I want to end up with is a formatted HTML page with headers for each parent and the children listed below, iterating right through the data structure. The Jade sample above is effectively what we need to output, but without hard-coding that in the view.
Mike's analysis in the comments of the problem being that of creating a table-like structure from a bunch of collections that haven't really got a lot in common is bang-on. The data is relational, but only within individual documents - so hard-coding the schema into anything is virtually impossible as it requires you to know what the data structure looks like first.
The basic idea is what #Gates VP described. I use underscore.js to iterate through the arrays/objects.
function formatLog(obj){
var log = "";
_.each(obj, function(val, key){
if(typeof(val) === "object" || typeof(val) === "array"){
// if we have a new list
log += "<ul>";
log += formatLog(val);
log += "</ul>";
}
else{
// if we are at an endpoint
log += "<li>";
log += (key + ": " + val);
log += "</li>";
}
});
return log;
}
If you call formatLog()on the example data you gave it returns
ServerAlias: GBIZ-WEBurltoken: CFID=10989&CFTOKEN=f07fe950-53926E3B-F33A-093D-3FCEFB&jsessionid=84303d29a229d1sessionid: 84197a667053f63433672873j377e7d379101UUID: 53934LBB-DB8F-79T6-C03937JD84HB864A338Template: /home/vagrant/dev/websites/g-bis/code/webroot/page/home/home.cfm, line 3GeneratedContent: Mailto: Message: Unknown tag: cfincflude.tagName: cfincfludeRAW_TRACE: at cfhome2ecfm1296628853.runPage(/home/vagrant/dev/websites/nig-bis/code/webroot/page/home/home.cfm:3)ID: CFINCLUDETEMPLATE: /home/vagrant/dev/websites/nig-bis/code/webroot/page/home/home.cfmLINE: 3TYPE: CFMLCOLUMN: 0RAW_TRACE: at cfdisplay2ecfm1093821753.runPage(/home/vagrant/dev/websites/nig-bis/code/webroot/page/display.cfm:6)ID: CFINCLUDETEMPLATE: /home/vagrant/dev/websites/nig-bis/code/webroot/page/display.cfmLINE: 6TYPE: CFMLCOLUMN: 0
How to format it then is up to you.
This is basically a recursive for loop.
To do this with Jade you will need to use mixins so that you can print nested objects by calling the mixin with a deeper level of indentation.
Note that this whole thing is a little ugly as you won't get guaranteed ordering of fields and you may have to implement some logic to differentiate looping on arrays vs. looping on JSON objects.
You can try util.inspect. In your template:
pre
= util.inspect(jsonResults)
I've created a snippet that pulls data from a databse table and displays it in tabular format. The snippet takes an id as parameter, and this is added to the sql query.
My problem is that if I've got more than 1 snippet call (sometimes need the tabular data for different id's displayed on a page) on the same page, all table data is the same as the last database call that's been made by the last snippet.
What do I need to do to kinda not cache the snippet database calls and have them all display their own content?
I've tried setting the page to no cache-able. Also used the [! !] brackets for the snippet calls, and even used the function_exists() method, but none of them helped.
Please can someone help me?
thanks
Try this at the end of the snippet:
mysql_connect('host', 'user', 'pass');
mysql_select_db('db_name');
You need to specify the connection parameters ofcourse.
It would help to answer if you can post your snippet. I do this with multiple calls on the page without issue, so there is either something wrong inside the snippet, or you need to output to unique placeholder names.
You have encountered a glitch of ModX, and it took me a long time to solve. ModX does a lot of caching by using hashing and apparently, when multiple connections are made from within one page divided over multiple snippets, this erratic behaviour can be seen. This is most likely very unwanted behaviour, it can be solved easily but gives you terrible headache otherways.
One sympton is that $modx->getObject($classname, $id)returns null (often).
The solution is very simple:
either use a static class with a single db instance, or
use $modx->setPlaceholder($instance, $tag);, or a combination.
My solution has been:
class dt__xpdo {
private function __construct() {}
public function __destruct() {
$this->close();
}
static public function db($modx = null) {
if ($modx->getPlaceholder('dt_xpdo') == '') {
$dt_user = 'xxxxxxxxx';
$dt_pw = 'xxxxxxxxx';
$dt_host = 'localhost';
$dt_dbname = 'xxxxxxxxx';
$dt_port = '3306';
$dt_dsn = "mysql:host=$dt_host;dbname=$dt_dbname;port=$dt_port;charset=utf8";
$dt_xpdo = new xPDO($dt_dsn, $dt_user, $dt_pw);
$dt_xpdo->setPackage('mymodel', MODX_CORE_PATH.'components/mymodel/'.'model/', '');
//$modx->log(modX::LOG_LEVEL_DEBUG, 'mymodel.config.php');
//$modx->log(modX::LOG_LEVEL_DEBUG, 'Could not addPackage for mymodel!');
$modx->setPlaceholder('dt_xpdo', $dt_xpdo);
}
return $modx->getPlaceholder('dt_xpdo');
}
}
Now you can use in your code:
require_once 'above.php';
and use something like
$xpdo = dt__xpdo::db($modx);
and continue flawlessly!