简体   繁体   中英

Update Mongo document field from Grails app

I have a requirement where I have to check in the database if the value of a boolean variable(crawled) is false. If so I have to set it to true. I am finding the record based on the value of a string variable(website). I referenced this link but it didn't help. Please tell me what I am doing wrong.

I tried this:

def p = Website.findByWebsite(website);
if(p['crawled'] == true) {
    println "already crawled"
} else {
    mongo.website.update( p, new BasicDBObject( '$set', new BasicDBObject( 'crawled', 'false' ) ) )
    println "updated object"
}

It gives me an error No such property: mongo for class: cmsprofiler.ResourceController

My domain class is as follows:

  class Website{
    String website
    User user
    Boolean crawled
    static belongsTo = [user: User]
    static constraints = {
        website( url:true, unique: ['user'])
    }
    static hasMany = [resource: Resource]
    static mapping = {resource cascade:"all-delete-orphan" }
}

you should be using

Website.mongo.update(...)

or let the framework inject it:

class ResourceController {
  def mongo

  def list(){
     mongo.website.update(...)
  }

}

This worked for me. Posting it here in case anyone else has similar requirement.

@Grab(group='com.gmongo', module='gmongo', version='0.9.3')
import com.gmongo.GMongo
@Transactional(readOnly = true)
class ResourceController {
    def mongo = new GMongo()
    def db = mongo.getDB("resources")
    def p = Website.findByWebsite(website)
    if(p['crawled']==false){
    db.website.update([crawled:false],[$set:[crawled:true]])
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM