首页 文章

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

提问于
浏览
4

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

这是我的模特:

//Game.js
module.exports = {  
   attributes: {
    name:{
       type: 'string',
       required: true
     },

   maps: {
      collection: 'map',
      via: 'game'
   }
}

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

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返回与游戏相关的 Map :

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

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

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' }, 
     name: 'map1',
     id: 'xxx300' } ]

谢谢!

2 回答

  • 1

    如果您想使用默认的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',
           required: true
         },
    
         maps: {
          collection: 'map',
          via: 'game'
         }
    
       }
    }
    

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

  • 0

    我想通了,如果我创建测试数据而不强制我想要的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' }, 
          name: 'map1',
          id: 'xxx300' 
         } 
     ]
    

相关问题