How exactly does findOrCreate() work?

450 views
Skip to first unread message

Stas Simovski

unread,
Mar 3, 2015, 6:20:18 AM3/3/15
to sai...@googlegroups.com
Let's say I have the following code:
var record = Node.findOrCreate(req.node.id,req.node).exec(function(err, node){
 
if(err) console.log(err);
  if(node) {
    res
.json(node);
  }
});
console.log(record); //returns undefined
if(record){
 
var nodeattrs = Object.getOwnPropertyNames(req.node);
  for(var prop in record){ //if properties from DB match request ones, update the DB entry
    if(_.contains(nodeattrs, prop)){
     
record.prop = nodeattrs.prop
    }
 
}
 
record.save();
}

Here I am assuming that findOrCreate() will NOT pass a node (i.e. record) to callback IF the "find" part succeeds. I am also assuming it would work like findOne(), where it would return the Record if it has been found and I can later call .save() on it, after I map the relevant parameters from the request. Clearly I am assuming wrong (docs are no help). The record is undefined, and the node seems to always be returned. So is the correct assertion that the findOrCreate() actually returns the node that it created AS WELL as the one it found, if it did at all? And can I call save() on that returned object and have it behave like an update to it's data?


Background:
I need to constantly save certain objects that the user manipulates (nodes on a diagram). The user can frequently add, remove and change the objects and then when the save is called clientside, it sends the current clientside object data to the server for update. If the data entry doesn't exist serverside, it should be created. If it does, it should be updated. Basically a little similar to Google Docs, just a lot simplier. 

Scott Gress

unread,
Mar 14, 2015, 2:42:19 PM3/14/15
to sai...@googlegroups.com
Hi Stas,

Your struggles here are with asynchronous programming, not findOrCreate.  Assigning a variable to the result of findOrCreate (or any asynchronous method) is essentially meaningless, and everything in your code from `console.log(record)` down is invalid as it will be run before the query.  You need to put all that logic in the callback, under `if (err)`.  Long story short, if you follow the docs, you should be in good shape! 

-Scott

Stas Simovski

unread,
Mar 14, 2015, 5:00:37 PM3/14/15
to sai...@googlegroups.com

Ahahaha that's right XD Such a stupid mistake even after all the years working with Ajax! Shows what I know. Although according to some design books these kind of mistakes (called "slips", being an incredibly professional term) are more common among experienced people than novices. Ah! What a wonderful excuse! 
Anyway thanks, that was a really dumb miss!
Reply all
Reply to author
Forward
0 new messages