创build并添加到集合,如果不存在sails.js
我对sails.js和node.js 都很陌生 ,所以这可能不是一个Sails的具体问题,但是我创build了一个User和Tag模型,这样User就有很多标签,反之亦然。 用户模型的相关属性是:
# models/User.js tags : { collection: 'Tag', via: 'users' }, add_tag: function( name ) { var self = this; Tag.findOne({ name: name }) .then( function( found ){ if( found ) { sails.log.info('found tag ' + found) found.users.add( self.id ); self.save( sails.log.info ); } else { sails.log.info('didnt find tag, creating with ' + self.id + ' and ' + name); Tag.create({ name: name, users: [ self.id ] }).exec( console.log ); } }); },
和标签模型:
name : { type: 'string', required: true, index: true }, users : { collection : 'User', via: 'tags' },
现在当我运行sails console
我使用以下testing:
sails> var user = null; User.find().exec( function( err, u ) { user= u[0]; }); undefined sails> user.add_tag('cataclysmic'); undefined sails> info: didnt find tag, creating with 2 and cataclysmic
在那里它挂起,直到我按Enter或Ctrl + C,并没有创build标签。
我再次对Node和Sails来自Rails背景,所以它可能是非常愚蠢的东西。 另外,如果我没有正确使用承诺,请让我知道,因为我对这些也很新。
更新
根据Travis Webb的build议,我试图转换为findOrCreate
,但它仍然不能工作:
add_tag: function( name ) { var self = this; Tag.findOrCreate({ name: name }) .then( function( tags ){ sails.log.info( JSON.stringify(tags) ); return tags; }).spread( function( tag ){ // should get the first matching tag sails.log.info( JSON.stringify(tag) ); Tag.update( { name: tag }, { user: self.id } ) .exec( sails.log.info ); }).catch( sails.log.error ); //no errors are logged either },
使用与上面相同的add_tag()
sails console
命令来调用add_tag()
我只是得到了undefined
并没有执行任何日志语句。 特拉维斯,我在这个实施中做错了什么?
最终更新
我用Jason的回答来创build我的最终答案:
add_tag: function( name ) { var self = this; Tag.findOrCreate({ name: name }, { name: name }) .then( function( tag ){ tag.users.add( self.id ); tag.save( sails.log.info ); }).catch( sails.log.error ); },
我的代码没有显示任何错误的原因是,我使用Tag.js中的生命周期callback来增加一个优先级计数器,每次更新都如此:
afterValidate: function() { this.priority++; }
当我应该一直在这样的链中调用下一个callback时:
afterValidate: function( values, cb ) { values.priority++; cb(); }
其中一件你不认为来自Rails背景的东西:P
你正在使用findOrCreate
。
函数定义是.findOrCreate( search criteria, [values, callback] )
你可能需要修改你的函数看起来像:
add_tag: function( name ) { var self = this; //for clarity we won't set the user when creating tags, //instead we'll do it in the callback, so its the same for existing and new tags. Tag.findOrCreate({ name: name }, { name: name }) .then( function( tag ){ tag.users.add( self.id ); tag.save( sails.log.info ); }); },