如何将数据插入多对多关联 sails js?

how to insert data into many to many association sails js?

我是 sails js 的新手,我想使用多对多关联向 mongodb 中插入数据,但我不知道应该先插入哪个集合以及如何插入。下面是我的模型:

// User.js
module.exports={
    attributes:{
        firstname:{
            type:'string'
        },
        lastname:{
            type:'string'
        },
        pets:{
            collection:'pet',
            via:'owners',
            dominant: true
        }
    }
};

// Pet.js
module.exports={
    attributes:{
        name:{
            type:'string'
        },
        type:{
            type:'string'
        },
        owners:{
            collection:'user',
            via:'pets'
        }
    }
};

我尝试先将数据插入宠物集合,但我没有看到集合已更新。这就是我将数据插入宠物集合的方式:

Pet.create({'name':req.body.name,'type':req.body.type}).exec(function(err,data){
  if(err) return next(err);
  res.json(data);
});

在此先感谢您的帮助

如果您有现有的用户记录,您可以在添加宠物时指定它们的数组:

Pet.create({
  'name':req.body.name,
  'type':req.body.type, 
  'owners': [userId1, userId2]
}).exec(function(err,data){
  if(err) { return next(err); ]
  res.json(data);
});

或者,您可以在添加新用户时指定新宠物的ID:

Pet.create({
  'name':req.body.name,
  'type':req.body.type
}).exec(function(err,newPet){
  if(err) { return next(err); ]
  User.create({ name: 'tom', pets: [newPet.id] }).exec(function(err, newUser) {
    if (err) { return next(err); }
    return res.json({ pet: newPet, user: newUser });
  });
});

之后,在 Sails 0.12.x 中,您可以使用 the associations docs. In Sails 1.0, you'd use the addToCollection, removeFromCollection and replaceCollection 方法中记录的方法从集合中 add/remove 项。