MongoMapper查询集合问题
当我定义用户 has_many 会议时,它会自动创建一个“user_id” 与用户集合相关的键/值对。除了我不能运行任何 mongo_mapper 查找使用此值,而不返回 nil 或 []。
Meeting.first(:user_id => "1234")
Meeting.all(:user_id => "1234")
Meeting.find(:user_id => "1234")
全部返回 nil。还有其他语法吗?基本上我无法对自动生成的关联 ObjectId 运行查询。
# Methods
class User
include MongoMapper::Document
key :user_name, String, :required => true
key :password, String
many :meetings
end
class Meeting
include MongoMapper::Document
key :name, String, :required => true
key :count, Integer, :default => 1
end
# Sinatra
get '/add' do
user = User.new
user.meetings "foobar") #should read: Meeting.new(:name => "foobar")
user.save
end
get '/find' do
test = Meeting.first(:user_id => "4b4f9d6d348f82370b000001") #this is the _id of the newly create user
p test # WTF! returns []
end
When I define the User has_many meetings, it automatically creates a "user_id"
key/value pair to relate to the User collections. Except I can't run any
mongo_mapper finds using this value, without it returning nil or [].
Meeting.first(:user_id => "1234")
Meeting.all(:user_id => "1234")
Meeting.find(:user_id => "1234")
All return nil. Is there another syntax? Basically I can't run a query on the automatically generated associative ObjectId.
# Methods
class User
include MongoMapper::Document
key :user_name, String, :required => true
key :password, String
many :meetings
end
class Meeting
include MongoMapper::Document
key :name, String, :required => true
key :count, Integer, :default => 1
end
# Sinatra
get '/add' do
user = User.new
user.meetings "foobar") #should read: Meeting.new(:name => "foobar")
user.save
end
get '/find' do
test = Meeting.first(:user_id => "4b4f9d6d348f82370b000001") #this is the _id of the newly create user
p test # WTF! returns []
end
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
正如 Jimmy 提到的有关检查 Meeting.all 的内容,我认为您不会有任何东西。
根据上面的示例,我发现了一些潜在的问题。
- 您的用户需要 :user_name,因此不会保存
- 永远不会被保存,因为您没有设置所需的名称
- 您的会议也没有被保存
- 另一件事,您需要将您的会议连接到 user.meetings
这适用于 mongo_mapper 0.6.10
您可能已经弄清楚了这一点,但我希望这无论如何都会有所帮助。
As Jimmy mentioned about checking Meeting.all, I don't think you would have anything.
Based on your example above I see a couple potential issues.
- Your User requires a :user_name so it's not getting saved
- would never get saved, because you didn't set the name which is required
- Your Meeting isn't getting saved either
- One more thing, you need to concat your meeting to user.meetings
This works with mongo_mapper 0.6.10
You may have figured this out already, but I hope this is helpful anyway.
您可以尝试使用
另外,如果您运行脚本/控制台,那么 Meeting.all 是否将每条记录显示为分配有 user_id?
You can try using
Also, if you run script/console then does Meeting.all show each record as having a user_id assigned to it?
仅 User.find("1234").meetings 怎么样?
What about just User.find("1234").meetings ?