微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

sails.js – Sails 0.10.x上的一对多关联无法使用populate检索所有者数据

我正在尝试使用sails 0.10.x和mongoDB创建一个简单的一对多关联.
我有两个模型,游戏和地图,游戏可以有多个与其帐户相关联的地图.
使用populate我可以正确地获得与游戏相关的所有地图,但逆操作不起作用.我无法使用Map中的填充来获取游戏数据.

这是我的模特:

//Game.js
module.exports = {  
   attributes: {
    name:{
       type: 'string',required: true
     },maps: {
      collection: 'map',via: 'game'
   }
}

//Map.js
module.exports = {
    attributes: {    
        name: {
           type: 'string',game:{
     model: 'game'
  }
}

//test data:
  Game.create({
    id: 200,name: 'game1'});

  Map.create({
    id: 300,name: 'map1',game: 200
  });

如果我使用

Game.find().populate("maps").exec(console.log);

它correclty返回与游戏相关的地图:

{ maps: 
 [ { name: 'map1',game: '200',id: '300' } ],name: 'game1'}

但是反向命令,试图从地图中检索游戏数据,返回一个未定义的游戏属性

Map.find().populate("game").exec(console.log)

收益:

{ name: 'map1',game: undefined,id: '300' }

即使尝试在find()中使用参数,我也得到了相同的结果.

用Sails和水线文档仔细检查了我的代码,但无法弄清楚我做错了什么.

文件http://sailsjs.org/#/documentation/concepts/ORM/Associations/OnetoMany.html

水线文件https://github.com/balderdashy/waterline-docs/blob/master/associations.md

UPDATE

我想通了,如果我创建测试数据而不强制我想要的ID,它可以很好地工作:

Game.create({name: 'game1'}).exec(console.log);

  Game.findOne({name: 'game1'},function (err,game){
    Map.create({
      name: 'map1',game: game.id
    }).exec(console.log);
  });

现在我可以获得所有者数据.由于它在我使用mongoDB id时有效,我相信这是与连接器有关的一些问题.

Map.find().populate("game").exec(console.log)
//returns (ommited the original IDs
   [ { game:
     { name: 'game1',id: 'xxx100' },id: 'xxx300' } ]

谢谢!

解决方法

如果您使用的是MongoDB并且不想使用认的Mongo ID,则需要 configure your models accordingly.例如:

//Game.js
module.exports = {  
   // Don't use automatic primary key
   autopK: false,attributes: {
    // Create your own ID field manually
     id: {
       type: 'integer',primaryKey: true
     },name:{
       type: 'string',via: 'game'
     }

   }
}

这将允许关联和其他操作正常工作.请注意,如果您这样做,那么您将负责保证唯一的整数ID; MongoDB没有“自动增量”属性.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐