I want to loop on a object to find what's the object name who have the socket id, and then when it's found console.log it
Code:
getUsernameBySocketID: function(socketid) {
for(var User in Users.Obj) {
var u = Users.Obj[User];
if(u.socketID == socketid) {
return u.username;
}
}
},
EDIT:
User.Obj :
I add elements to user.obj with a function to create a new user:
Users.Obj[id] = new Users.User({username: username, socketID: socketID});
and Users.User contains :
User: function(data) {
this.username = data.username;
this.socketID = data.socketID;
},
but when I call the function and console.log it, it return nothing.
How can I solve that ? Thanks
Finally I've found my problem using #Watte's help
Users.Obj were just empty
Related
Multiple entity records have to be deleted in one call instead of multiple callbacks so trying to use Xrm.WebApi.online.executeMultiple to delete records. but the code written below is not working. Any help will be appreciated.
for (var i=0; i<Checkbox.length; i++)
{
if(Checkbox[i].checked)
{
var id = Checkbox[i].value;// GUID of the record to be deleted
Checkbox[i].checked = false;
DeleteRequests[i]={};
DeleteRequests[i].getMetadata = function(){
return{
boundParameter: undefined,
operationType: 2,
operationName: "Delete",
parameterTypes: {
}
}
}
DeleteRequests[i].etn="cme_entity";
DeleteRequests[i].payload=id;
}
}
window.parent.Xrm.WebApi.online.executeMultiple(DeleteRequests).then(
function (results) {alert("Success");},
function (error) {alert("Failed");});
Getting weird error that this operation could not be processed. Please contact Microsoft.
The issue has to do with how you are constructing the delete request objects. You need to declare a function that sets up the getMetadata function and the required entityReference object.
I've tested the below solution and it works.
var Sdk = window.Sdk || {};
Sdk.DeleteRequest = function (entityReference) {
this.entityReference = entityReference;
this.getMetadata = function () {
return {
boundParameter: null,
parameterTypes: {},
operationType: 2,
operationName: "Delete",
};
};
};
for (var i = 0; i < Checkbox.length; i++) {
if (Checkbox[i].checked) {
var id = Checkbox[i].value;
Checkbox[i].checked = false;
DeleteRequests[i] = new Sdk.DeleteRequest({ entityType: "account", id: id });
}
}
window.parent.Xrm.WebApi.online.executeMultiple(DeleteRequests).then(
function (results) { alert("Success"); },
function (error) { alert("Failed"); });
Unfortunately CRUD operations with Xrm.WebApi.online.execute and Xrm.WebApi.online.executeMultiple are not very well documented. I've written a blog post with some code samples.
The important parts are the declaration of the Sdk.DeleteRequest function as a property on window and instantiating a request object using new Sdk.DeleteRequest(). I experimented a little and determined that just simply creating a request object like you were doing before, even with the right attributes does not work either.
Hope this helps! :)
Comanda.findOneAndUpdate(id,{$set: {"orden.0.fondos.2.estadoitem": estado}}, {}, function(err, comanda)
I need to indirectly change that "2" in
$set: {"orden.0.fondos.2.estadoitem"
no matter what I do, i cant.. this will save my live =/..
i have tried everything, calling a var pos = 2; and then $set: {"orden.0.fondos.pos.estadoitem" also as a string pos= "2"; and nothing seems to work
thanks in advace
You can create $set field dynamically :
var set = { "$set": {} };
set.$set["orden.0.fondos." + pos + ".estadoitem"] = estado;
Comanda.findOneAndUpdate(id, set, {}, function(err, comanda) {
})
Seems orden is an array and so is fondos.
You could try
var doc = findOne({_id: id});
doc.orden[0].fondos[2] = 'anything you want';
doc.save((err,result)=>{})
I am new to Parse and Cloud Code, but I have managed to write a few AfterSave Cloud Code functions that work fine. However, I am having a lot of trouble with this one, and I cannot figure out why. Please help...
I have
Two PFObject classes: Message and MessageThread
Message contains chat messages that are associated with a MessageThread
MessageThread contains an array of members (which are all PFUsers)
Upon insert to Message, I want to look up all the members of the related MessageThread and Push notifications to them
class MessageThread: PFObject {
#NSManaged var members: [PFUser]
#NSManaged var lastMessageDate: NSDate?
#NSManaged var messageCount: NSNumber?
override class func query() -> PFQuery? {
let query = PFQuery(className: MessageThread.parseClassName())
query.includeKey("members")
return query
}
init(members: [PFUser], lastMessageDate: NSDate?, messageCount: NSNumber?) {
super.init()
self.members = members
self.lastMessageDate = lastMessageDate
self.messageCount = messageCount
}
override init() {
super.init()
}
}
extension MessageThread: PFSubclassing {
class func parseClassName() -> String {
return "MessageThread"
}
override class func initialize() {
var onceToken: dispatch_once_t = 0
dispatch_once(&onceToken) {
self.registerSubclass()
}
}
}
class Message: PFObject {
#NSManaged var messageThreadParent: MessageThread
#NSManaged var from: PFUser
#NSManaged var message: String
#NSManaged var image: PFFile?
override class func query() -> PFQuery? {
let query = PFQuery(className: Message.parseClassName())
query.includeKey("messageThreadParent")
return query
}
init( messageThreadParent: MessageThread, from: PFUser, message: String, image: PFFile?) {
super.init()
self.messageThreadParent = messageThreadParent
self.from = from
self.message = message
self.image = image
}
override init() {
super.init()
}
}
extension Message: PFSubclassing {
class func parseClassName() -> String {
return "Message"
}
override class func initialize() {
var onceToken: dispatch_once_t = 0
dispatch_once(&onceToken) {
self.registerSubclass()
}
}
}
Approach
From the request object (a Message), get its messageThreadParent
Lookup the members of the parent MessageThread, loop through them, etc.
The problem
When I try to retrieve the MessageThread object, I attempt to query on Id == threadParent.objectId. However, this query always returns all 8 of my current MessageThreads, rather than the single one I need.
Parse.Cloud.afterSave(Parse.Object.extend("Message"), function(request) {
Parse.Cloud.useMasterKey();
var theMsg = request.object;
var threadParent;
var currUsername = request.user.get("username");
var threadUsers;
var usernameArray;
threadParent = request.object.get("messageThreadParent");
// promise
queryM = new Parse.Query(Parse.Object.extend("MessageThread"));
queryM.include("members");
queryM.equalTo("id", threadParent.objectId);
queryM.find().then(function (threadParam) {
console.log(" threads: ");
console.log(threadParam.length); //this returns 8, which is the number of threads I have. I would expect just 1, matching threadParent.objectId...
console.log("thread is: ");
//... additional code follows, which seems to work...
After grappling with a separate problem all day I finally figured out that in Parse's Javascript SDK there is a difference between "id" and "objectId".
Changing this
queryM.equalTo("id", threadParent.objectId); // doesn't work
to
queryM.equalTo("objectId", threadParent.id); // works!
fixed my problem.
Here is a weird bug I am having. First here is my code
User = {};
User._defaults = {
emails : [],
enabled : true
}
User.defaults = function(){
var defaults = _.clone(User._defaults);
return _.extend(defaults,{
createdAt : new Date()
});
}
Accounts.onCreateUser(function(options, user){
console.log(User.defaults());
// returns {emails: [ { address: 'francis#domain.com', verified: true } ], enabled: true}
_.defaults(user, User.defaults());
user.emails.push(user.services.linkedin.emailAddress);
return user;
});
As you can see, when I call User.defaults() it returns an object with the emails array filled with the email address of the previous new use.
But what is even weirder, is that when I do this :
Accounts.onCreateUser(function(options, user){
console.log(User._defaults, User.defaults());
user.enabled = true;
user.emails = [];
user.createdAt = new Date();
// _.defaults(user, User.defaults());
user.emails.push(user.services.linkedin.emailAddress);
return user;
})
The logged User.defaults() actually return an object with the emails array empty.
Anyone has an idea what can cause this ??
Thanks !!
This would have to do with the Underscore clone function. If you read the docs.
Create a shallow-copied clone of the provided plain object. Any nested
objects or arrays will be copied by reference, not duplicated.
The important part is the shallow copy. Your array is not an actual copy, it's just a reference. So you are always referring to the same array every time.
I would do the following.
User = {};
User.defaults = function(){
return {
emails : [],
enabled : true,
createdAt : new Date()
}
}
I am parsing an array of objects, and there's about 12 fields in each. I am doing this with two nested for(var i = 0; i < array.length; i++) functions, and ran into a null field several responses in.
I am expecting to get an embedded object, ... "caption": {"id":"some id", "text":"some text"}, but am instead getting a null in some cases. My schema does not require the field to have a value, but the document is getting kicked out.
How can I get around this? Would expect the null just to insert a blank value, but that is not the case. I am working within the Meteor.js framework, but the snippet I need help with below is just plain old javascript and a mongodb upsert. The error is on the caption.text line.
Meteor.methods({
'getMethod': function (var1, var2) {
check (var1, Number);
this.unblock();
var url = "https://www.url.com/"+var1+"/stuff?"+token+"¶m="+var2;
var result = HTTP.call("GET", url);
if(result.statusCode===200) {
var aArray = JSON.parse(result.content).data;
for(var i = 0; i < aArray.length; i++){
var id = aArray[i].id;
var aItem = {
_id: aArray[i].id,
userId: aArray[i].user.id,
username: aArray[i].user.username,
created_time: parseInt(aArray[i].created_time),
type: aArray[i].type,
caption: aArray[i].caption.text, // THIS LINE IS THROWING THE ERROR !!
}
Collection.upsert(id, {$set: aItem}, {validationContext: 'upsertForm'}, function(error, result) {
if (error){
console.log("Error:", error);
return aArray;
}
});
}
} else {
console.log("Error: ", result.statusCode);
var errorJson = JSON.parse(result.content);
throw new Meteor.Error(result.statusCode, errorJson.error);
}
},
});
Use a ternary to check if there's a text property on the caption:
caption: (aArray[i].caption.text) ? aArray[i].caption.text : ''
Edit : If the caption property is questionable, then use the following:
caption: (aArray[i].caption) ? aArray[i].caption.text : ''
h/t RobG