Grails MongoDb:使用domain作为值保存地图值失败

时间:2014-03-25 19:01:29

标签: mongodb grails

我有2个域类,User和Dog(例如)

class User { 
    String id
    Map<String, Dog> dogs
} 

class Dog {
    String name
}

我的控制器将json作为输入

{"key" : "dogKey", "userId" : "someId", "dogName" : "dog"}

def addDog(){
    String key = request.JSON.key
    User user = User.get(request.JSON.userId)
    String dogName = request.JSON.dog
    ...
    if(! user.dogs){
        user.dogs = new HashMap<>(1)
    }

    user.dogs.put(key, new Dog(name: dogName))
    user.save(flush: true)
}

运行用户数据@ Mongo后:

用户:

{   _id:....,
    dogs: {
        "dogKey": null
    }...
}

有人可以解释一下我错过了什么吗?

谢谢!

罗伊

1 个答案:

答案 0 :(得分:0)

可能是狗参考不保存在数据库中

 def addDog(){
        String key = request.JSON.key
        User user = User.get(request.JSON.userId)
        String dogName = request.JSON.dog
        ...
        if(! user.dogs){
            user.dogs = new HashMap<>(1)
        }
        Dog dog =  new Dog(name: dogName)
          dog.save(flush:true)
        user.dogs.put(key, dog)
        user.save(flush: true)
    }