I have a requirement to create a new object in the DB, but the object is
represented by 2 tables with a many to many relationship (the object itself
can be described by many attributes). So, I have a create method for the
object, and I would like the method to be able to return some JSON similar
to "{objectid:1, objectname:'blah', attribs:[{attribid:1,
attribval:'blah'}, {attribid:2, attribval:'blah'}]}".
The naive approach would be to do something like -
exports.create = function(objectname, attribs, callback) {
dbclient.query(
'INSERT INTO object (objectname) values (?)',
[objectname],
function(err, results) {
var obj = {
objectid: results.insertId,
objectname; objectname,
attribs: []
};
attribs.forEach(
function(element, index, array){
//naively add the attrib before we're sure that they've been added in the db
obj.attribs.push({attribid: element.id, attribval: element.val});
dbclient.query(
'INSERT INTO object_attribs (objectid, attribid, val) values (?, ?, ?)'
[obj.objectid, element.attribid, element.val],
function(err, results){
//do nothing here
}
);
};
);
callback(err, obj);
}
);
}
But, due to the asynchronous nature of nodejs, I would be returning obj
before all of the attribs had actually been committed in the DB. Even
worse would be if I actually were creating the attribs and needed to get
the ids of the new attribs from the DB before returning obj.
The only solution I can think of here is to either do a SP, or make the
addition/creation of attribs a separate method call to nodejs. Neither of
these two options sounds great. How do you solve this problem?
Thanks
Martin
--
Job Board: http://jobs.nodejs.org/
Posting guidelines:
https://github.com/joyent/node/wiki/Mailing-List-Posting-Guidelines
You received this message because you are subscribed to the Google
Groups "nodejs" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to
[email protected]
For more options, visit this group at
http://groups.google.com/group/nodejs?hl=en?hl=en