Mongoid批量插入不使用key
我正在将 Mongoid 用于一个项目,并尝试通过执行以下操作来使用批量插入功能:
Person.collection.insert(friends)
其中朋友是哈希数组。
不幸的是,我正在尝试使用 Mongoid 的关键功能将每个对象的 ID 设置为其 Facebook 用户 ID。这是代码:
def process_friends(type, friends)
unless friends
@graph = Koala::Facebook::API.new(self.token)
friends = @graph.get_connections('me','friends', {'fields' => 'id,name,picture,education,location,gender'})
end
friends.each do |friend|
friend[:u_id] = friend["id"]
friend.delete "id"
end
Person.collection.insert(friends)
self.update_attributes( process_status: {status: "success", type: type})
end
在我的 Person 模型定义中:
key :u_id
当我循环所有朋友并单独添加它们时,它正在工作,但现在我已经进行了批量插入,它不会将每个 Person 的 id 设置为 u_id。
有什么想法吗?
I'm using Mongoid for a project and am trying to use the batch insert feature by doing:
Person.collection.insert(friends)
Where friends is an array of hashes.
Unfortunately, I'm trying to use key function of Mongoid to set each object's ID to their Facebook user id. Here is the code:
def process_friends(type, friends)
unless friends
@graph = Koala::Facebook::API.new(self.token)
friends = @graph.get_connections('me','friends', {'fields' => 'id,name,picture,education,location,gender'})
end
friends.each do |friend|
friend[:u_id] = friend["id"]
friend.delete "id"
end
Person.collection.insert(friends)
self.update_attributes( process_status: {status: "success", type: type})
end
and in my Person model definition:
key :u_id
It was working when I was looping over all the friends and adding them individually, but now that I've gone to a batch insert it's not setting each Person's id to the u_id.
Any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
Model.collection 检索内部(ruby 驱动程序)集合而不是使用 mongoid。批量插入需要以这种方式完成,因为 mongoid 本身不支持它。
本质上,通过直接访问集合,您绕过了 mongoid,因此声明
key :u_id
的事实不会(也不应该)产生任何效果。解决方案是仅使用
_id
而不是 u_id,这样驱动程序就不会尝试为您生成一个。但是,这可能会对代码中的其他地方产生影响。
如果您很懒,另一种解决方案是不关心额外的 object_id 并让驱动程序为您创建一个。
Model.collection retrieves the internal (ruby driver) collection instead of using mongoid. Batch insert needs to be done that way because it is not supported by mongoid itself.
Essentially, by accessing the collection directly, you are bypassing mongoid and so the fact that you declare
key :u_id
doesn't (and shouldn't) have any effect.The solution is to just use
_id
instead of u_id so that the driver doesn't try to generate one for you.However, this may have implications elsewhere in your code.
Another solution, if you are lazy, is to just not care about the extra object_id and let the driver create one for you.