Saving in mongoDb with Mongoose, unexpected elements saved - mongodb

When I write in my mongoDB with mongoose the operation is treated with success, my document is saved, but there is also all kind of weird other sutff written down. It seems to be mongoose code. What could cause this?
I add stuff in a specific array with:
resultReference.ref[arrayLocation].allEvents.push(theEvent);
{id: 11, allEvents: [] } is the structure of a ref element, and I push theEvent in the allEvents array. I then resultReference.save()
I use express, mongoose and mongoHQ for database. I tried on a local mongo server, and this annoyance is still there. I've print in my console the document to write before save() and non of this weird code is there.
{
id 11
allEvents
[
0
{
_events
{
maxListeners 0
}
_doc
{
_id {"$oid": "4eb87834f54944e263000003"}
title "Test"
allDay false
start 2011-11-10 13:00:00 UTC
end 2011-11-10 15:00:00 UTC
url "/test/4eb87834f54944e263000002"
color "#99CCFF"
ref "4eb87834f54944e263000002"
}
_activePaths
{
paths
{
title "modify"
allDay "modify"
start "modify"
end "modify"
url "modify"
color "modify"
ref "modify"
}
states
{
init
{ }
modify
{
title true
allDay true
start true
end true
url true
color true
ref true
}
require
{ }
}
stateNames
[
0 "require"
1 "modify"
2 "init"
]
}
_saveError null
_validationError null
isNew true
_pres
{
save
[
0
function (next) {
// we keep the error semaphore to make sure we don't
// call `save` unnecessarily (we only need 1 error)
var subdocs = 0
, error = false
, self = this;
var arrays = this._activePaths
.map('init', 'modify', function (i) {
return self.getValue(i);
})
.filter(function (val) {
return (val && val instanceof DocumentArray && val.length);
});
if (!arrays.length)
return next();
arrays.forEach(function (array) {
subdocs += array.length;
array.forEach(function (value) {
if (!error)
value.save(function (err) {
if (!error) {
if (err) {
error = true;
next(err);
} else
--subdocs || next();
}
});
});
});
}
1 "function checkForExistingErrors(next) {
if (self._saveError){
next(self._saveError);
self._saveError = null;
} else {
next();
}
}"
2 "function validation(next) {
return self.validate.call(self, next);
}"
]
}
_posts
{
save
[ ]
}
save
function () {
var self = this
, hookArgs // arguments eventually passed to the hook - are mutable
, lastArg = arguments[arguments.length-1]
, pres = this._pres[name]
, posts = this._posts[name]
, _total = pres.length
, _current = -1
, _asyncsLeft = proto[name].numAsyncPres
, _next = function () {
if (arguments[0] instanceof Error) {
return handleError(arguments[0]);
}
var _args = Array.prototype.slice.call(arguments)
, currPre
, preArgs;
if (_args.length && !(arguments[0] === null && typeof lastArg === 'function'))
hookArgs = _args;
if (++_current < _total) {
currPre = pres[_current]
if (currPre.isAsync && currPre.length < 2)
throw new Error("Your pre must have next and done arguments -- e.g., function (next, done, ...)");
if (currPre.length < 1)
throw new Error("Your pre must have a next argument -- e.g., function (next, ...)");
preArgs = (currPre.isAsync
? [once(_next), once(_asyncsDone)]
: [once(_next)]).concat(hookArgs);
return currPre.apply(self, preArgs);
} else if (!proto[name].numAsyncPres) {
return _done.apply(self, hookArgs);
}
}
, _done = function () {
var args_ = Array.prototype.slice.call(arguments)
, ret, total_, current_, next_, done_, postArgs;
if (_current === _total) {
ret = fn.apply(self, args_);
total_ = posts.length;
current_ = -1;
next_ = function () {
if (arguments[0] instanceof Error) {
return handleError(arguments[0]);
}
var args_ = Array.prototype.slice.call(arguments, 1)
, currPost
, postArgs;
if (args_.length) hookArgs = args_;
if (++current_ < total_) {
currPost = posts[current_]
if (currPost.length < 1)
throw new Error("Your post must have a next argument -- e.g., function (next, ...)");
postArgs = [once(next_)].concat(hookArgs);
return currPost.apply(self, postArgs);
}
};
if (total_) return next_();
return ret;
}
};
if (_asyncsLeft) {
function _asyncsDone (err) {
if (err && err instanceof Error) {
return handleError(err);
}
--_asyncsLeft || _done.apply(self, hookArgs);
}
}
function handleError (err) {
if ('function' == typeof lastArg)
return lastArg(err);
if (errorCb) return errorCb.call(self, err);
throw err;
}
return _next.apply(this, arguments);
}
errors null
}
]
}
]

The reason this happened is because I didnt save my schema in mongoose in the proper order. This would mean declaring your child schema before a parent to get proper behavior.

Related

w2ui filter option "contains not" possible?

I am using w2ui (1.5) and I would be interested in whether it is possible to use a filter that only delivers negative results
That means only records/keys which not fullfilling a certain criteria.
Like a condition "contains not" or "is not" in addition to
http://w2ui.com/web/docs/1.5/w2grid.textSearch.
Thanks!
Gordon
okay, a possible solution is
w2ui['grid'].search([{ field: var1, value: var2, operator: 'not in'}], 'OR');
I coded my own solution to this problem. This adds a way to use "not" for string and "!=" for number searches.
This function does the search and it is also used to store the grid advanced search popup in history state.
I'm sure this can be even more optimized, so please use this more like a guideline. Hope this helps somebody.
function searchExtend(event, grid) {
// if event is null, we do just the local search
var searchObj;
if (event == null) {
searchObj = grid;
} else {
searchObj = event;
}
// make a copy of old data
const oldSearchData = structuredClone(searchObj.searchData);
const oldSearchLogic = structuredClone(searchObj.searchLogic);
var searchData = searchObj.searchData;
var invertedSdata = [];
var toSplice = [];
// check operator if it's "not" or "!="
for (var i = 0; i < searchData.length; i++) {
var sdata = searchData[i];
// invert the condition
if (sdata.operator == "not") {
toSplice.push(i);
invertedSdata.push({
field: sdata.field,
type: sdata.type,
operator: "contains",
value: sdata.value
});
}
if (sdata.operator == "!=") {
toSplice.push(i);
invertedSdata.push({
field: sdata.field,
type: sdata.type,
operator: "=",
value: sdata.value
});
}
}
// remove all "not" and "!=" from searchData
for (var i in toSplice) {
searchData.splice(i, 1);
}
var foundIds = [];
// use inverted criteria to search
if (invertedSdata.length > 0) {
grid.searchData = invertedSdata;
grid.searchLogic = "OR";
grid.localSearch();
grid.searchLogic = oldSearchLogic;
// store found ids
foundIds = structuredClone(grid.last.searchIds);
}
if (foundIds.length > 0) {
// perform a search with original criteria - spliced "not" and "!="
grid.searchData = searchData;
grid.localSearch();
var allRecIds = structuredClone(grid.last.searchIds);
// if there's not any results, push push all recIds
if (grid.last.searchIds.length == 0) {
for (let i = 0; i < grid.records.length; i++) {
allRecIds.push(i);
}
}
// remove all ids found with inverted criteria from results. This way we do the "not" search
for (const id of foundIds) {
allRecIds.splice(allRecIds.indexOf(id), 1);
}
if (event != null) {
// let the search finish, then refresh grid
event.onComplete = function() {
refreshGrid(grid, allRecIds, oldSearchData);
setSearchState(grid);
}
} else {
// refresh the grid
refreshGrid(grid, allRecIds, oldSearchData);
setSearchState(grid);
}
return;
}
if (event != null) {
event.onComplete = function() {
setSearchState(grid); // store state
}
} else {
// refresh whole grid
refreshGrid(grid, allRecIds, oldSearchData);
setSearchState(grid);
}
}
function refreshGrid(grid, allRecIds, oldSearchData) {
grid.last.searchIds = allRecIds;
grid.total = grid.last.searchIds.length;
grid.searchData = oldSearchData;
grid.refresh();
}
function setSearchState(grid) {
history.replaceState(JSON.stringify(grid.searchData), "Search");
}
To use this, you have to call it from the grid's onSearch:
onSearch: function(event) {
searchExtend(event, w2ui["grid"]);
}
Also, if you want to use the history.state feature, it needs to be called from onLoad function:
onLoad: function(event) {
event.onComplete = function() {
console.log("History state: " + history.state);
if (history.state != null) {
w2ui["grid"].searchData = JSON.parse(history.state);
searchExtend(null, w2ui["grid"]);
}
}
To add operators, please use this reference.
This is my solution to the problem:
operators: {
'text': ['is', 'begins', 'contains', 'ends', 'not'], // could have "in" and "not in"
'number': ['=', 'between', '>', '<', '>=', '<=', '!='],
'date': ['is', 'between', {
oper: 'less',
text: 'before'
}, {
oper: 'more',
text: 'after'
}],
'list': ['is'],
'hex': ['is', 'between'],
'color': ['is', 'begins', 'contains', 'ends'],
'enum': ['in', 'not in']
}

how to collect data from user with the facebook messenger bot api in node js

I am building a messenger bot in node. I want it to collect user input data and have a conversation or ask questions, but the code I have doesn't work. the part that does not work is it only continues to the next else if block if i type the same code. and second the array is not capturing the text after the first if statement. Is there a better way to do it? Could someone provide code?
My code is below. what i want is like in this iimage:
var currentbot = 0;
var awnswers = [];
app.post('/webhook', function(req, res) {
var events = req.body.entry[0].messaging;
for (i = 0; i < events.length; i++) {
var event = events[i];
if (event.message && event.message.text) {
var text = event.message.text;
if (text == "hi") {
start(event.message.text, event.sender.id);
}
}
}
res.sendStatus(200);
});
var awnswers = [];
function start(text, id) {
if (count == 0) {
sendTextMessage('hello lets order!', id);
arr.push(text);
console.log(awnswers);
count = 1;
} else if (count == 1) {
sendTextMessage('what size do you want?', id);
arr.push(text);
console.log(awnswers);
count = 2;
} else if (count == 2) {
sendTextMessage('its on its way!', id);
arr.push(text);
console.log(awnswers);
count = 0;
}
}
function sendTextMessage(messageText, recipientId) {
var messageData = {
recipient: {
id: recipientId
},
message: {
text: messageText
}
};
callSendAPI(messageData);
}
function callSendAPI(messageData) {
request({
uri: 'https://graph.facebook.com/v2.6/me/messages',
qs: {
access_token: process.env.access_token
},
method: 'POST',
json: messageData
}, function(error, response, body) {
if (!error && response.statusCode == 200) {
var recipientId = body.recipient_id;
var messageId = body.message_id;
console.log("Successfully sent generic message with id %s to recipient %s", messageId, recipientId);
} else {
console.error("Unable to send message.");
console.error(response);
console.error(error);
}
});
}
The main issues I think I see are:
Start() is only called when text == hi
Count is not defined
You're pushing to the array 'arr' not, awnswers
You can fix these by:
Calling start() on every message
Defining count like var count = 0; at the top of your file, next to var currentbot
awnswers.push(text);

How to pass a test if expect fails

I have this code
it('This should pass anyway', function (done) {
testObj.testIt(regStr);
});
testObj
this.testIt = function (regStr) {
selector.count().then(function (orgCount) {
for (var curr = 0; curr < count; curr++) {
checkField(curr, regStr);
}
});
};
function checkField(curr, regStr) {
selector.get(curr).all(by.tagName('li')).get(0).getInnerHtml().then(function (text) {
expect(text).to.match(regStr, curr + '#ERR');
});
}
If one of these expects get a failure, test fails. How can i handle this? I mean - can i somehow count passed and failed expect()ations and return it? or, at least, dont let test break on first error.
I've tried try-catch, but nothing good happened.
it('This should pass anyway', function (done) {
try {
testObj.testIt(regStr);
} catch (e) {
console.log('#err' + e);
}
});
And then i wanted to use done(), but havent found any examples to do the similar. Can u please help me?
Sry for my english
UPD
You can return either null or a string from checkField(), join them up, and expect the array to be empty:
this.testIt = function (regStr) {
selector.count().then(function (orgCount) {
var errors = [];
for (var curr = 0; curr < orgCount; curr++) {
var e = checkField(curr, regStr);
if (e) { errors.push(e); }
}
assert.equal(0, errors.length, errors);
});
};
A cleaner approach would be to use map() to collect the data into an array:
var data = selector.map(function (elm) {
return elm.element(by.tagName('li')).getText();
});
expect(data).toEqual(["test1", "test2", "test3"]);

why my function call many time , with bootstrap modal?

My JS :
$("#modalADDpp").on('shown',function(e){
$(this).find('input[type=text]').filter(':first').focus();
var count = 0;
alert(count);
$('#pp_tab a').click(function () {
$(this).tab('show');
})
$("#TenPP").typing({ // jquery for check when finish typing
start: function(event ,$elem) {
$(".add-on").remove();
return false;
},
stop: function (event, $elem) {
count ++;
alert(count);
if(count == 1 )
{
Ajax_Check_Name($elem);// Check name same with database by ajax
}
return false;
},
delay: 500
});
$("#modalADDpp").on('hidden',function(e){
$(this).closest('form').find("input[type=text], textarea").val("");
$(".add-on").remove();
});
});
I crate $count = 0 at my modal shown . At first time , it work ok . But when hide modal and re-open , $count not = 0 , $count now = 2 => my function will call two time and if close agains , it plus to 3 , 4 ,5 times .
I use
if(count == 1 )
because i want it run only one time .So it work ok but I dont know where is problem . Need Help !!!
Code of typing.js
(function ($) {
//--------------------
// jQuery extension
//--------------------
$.fn.typing = function (options) {
return this.each(function (i, elem) {
listenToTyping(elem, options);
});
};
//-------------------
// actual function
//-------------------
function listenToTyping(elem, options) {
// override default settings
var settings = $.extend({
start: null,
stop: null,
delay: 400
}, options);
// create other function-scope variables
var $elem = $(elem),
typing = false,
delayedCallback;
// start typing
function startTyping(event) {
if (!typing) {
// set flag and run callback
typing = true;
if (settings.start) {
settings.start(event, $elem);
}
}
}
// stop typing
function stopTyping(event, delay) {
if (typing) {
// discard previous delayed callback and create new one
clearTimeout(delayedCallback);
delayedCallback = setTimeout(function () {
// set flag and run callback
typing = false;
if (settings.stop) {
settings.stop(event, $elem);
}
}, delay >= 0 ? delay : settings.delay);
}
}
// listen to regular keypresses
$elem.keypress(startTyping);
// listen to backspace and delete presses
$elem.keydown(function (event) {
if (event.keyCode === 8 || event.keyCode === 46) {
startTyping(event);
}
});
// listen to keyups
//$elem.keyup(stopTyping);
// listen to blurs
$elem.blur(function (event) {
stopTyping(event, 0);
});
}
})(jQuery);
try to reset the count to 0 ... on hidden or in stop function ...
if(count == 1 )
{
Ajax_Check_Name($elem);// Check name same with database by ajax
count = 0;
}
Or
$("#modalADDpp").on('hidden',function(e){
$(this).closest('form').find("input[type=text], textarea").val("");
$(".add-on").remove();
count = 0;
});

TypeError: 'undefined' is not a function (evaluating 'ime.registIMEKey()')

Despite of setting and defining everything in Samsung smart TV SDK 4.0 I am getting this error:
TypeError: 'undefined' is not a function (evaluating 'ime.registIMEKey()')
Please help!
CODE:
var widgetAPI = new Common.API.Widget();
var tvKey = new Common.API.TVKeyValue();
var wapal_magic =
{
elementIds: new Array(),
inputs: new Array(),
ready: new Array()
};
/////////////////////////
var Input = function (id, previousId, nextId) {
var previousElement = document.getElementById(previousId),
nextElement = document.getElementById(nextId);
var installFocusKeyCallbacks = function () {
ime.setKeyFunc(tvKey.KEY_UP, function (keyCode) {
previousElement.focus();
return false;
});
ime.setKeyFunc(tvKey.KEY_DOWN, function (keyCode) {
nextElement.focus();
return false;
});
ime.setKeyFunc(tvKey.KEY_RETURN, function (keyCode) {
widgetAPI.blockNavigation();
return false;
});
ime.setKeyFunc(tvKey.KEY_EXIT, function (keyCode) {
widgetAPI.blockNavigation();
return false;
});
}
var imeReady = function (imeObject) {
installFocusKeyCallbacks();
wapal_magic.ready(id);
},
ime = new IMEShell(id, imeReady, 'en'),
element = document.getElementById(id);
}
wapal_magic.createInputObjects = function () {
var index,
previousIndex,
nextIndex;
for (index in this.elementIds) {
previousIndex = index - 1;
if (previousIndex < 0) {
previousIndex = wapal_magic.inputs.length - 1;
}
nextIndex = (index + 1) % wapal_magic.inputs.length;
wapal_magic.inputs[index] = new Input(this.elementIds[index],
this.elementIds[previousIndex], this.elementIds[nextIndex]);
}
};
wapal_magic.ready = function (id) {
var ready = true,
i;
for (i in wapal_magic.elementIds) {
if (wapal_magic.elementIds[i] == id) {
wapal_magic.ready[i] = true;
}
if (wapal_magic.ready[i] == false) {
ready = false;
}
}
if (ready) {
document.getElementById("txtInp1").focus();
}
};
////////////////////////
wapal_magic.onLoad = function()
{
// Enable key event processing
//this.enableKeys();
// widgetAPI.sendReadyEvent();
this.initTextBoxes(new Array("txtInp1", "txtInp2"));
};
wapal_magic.initTextBoxes = function(textboxes){
this.elementIds = textboxes;
for(i=0;i<this.elementIds.length;i++){
this.inputs[i]=false;
this.ready[i]=null;
}
this.createInputObjects();
widgetAPI.registIMEKey();
};
wapal_magic.onUnload = function()
{
};
wapal_magic.enableKeys = function()
{
document.getElementById("anchor").focus();
};
wapal_magic.keyDown = function()
{
var keyCode = event.keyCode;
alert("Key pressed: " + keyCode);
switch(keyCode)
{
case tvKey.KEY_RETURN:
case tvKey.KEY_PANEL_RETURN:
alert("RETURN");
widgetAPI.sendReturnEvent();
break;
case tvKey.KEY_LEFT:
alert("LEFT");
break;
case tvKey.KEY_RIGHT:
alert("RIGHT");
break;
case tvKey.KEY_UP:
alert("UP");
break;
case tvKey.KEY_DOWN:
alert("DOWN");
break;
case tvKey.KEY_ENTER:
case tvKey.KEY_PANEL_ENTER:
alert("ENTER");
break;
default:
alert("Unhandled key");
break;
}
};
The registIMEKey method is part of the Plugin API.
var pluginAPI = new Common.API.Plugin();
pluginAPI.registIMEKey();
See: http://www.samsungdforum.com/Guide/ref00006/common_module_plugin_object.html#ref00006-common-module-plugin-object-registimekey
Edit: Updated to add code solution.
widgetAPI no contains method registIMEKey();, it contains in IMEShell.