R Shiny App编辑MongoDB

时间:2018-03-27 16:32:49

标签: r mongodb shiny mongolite

我有一个使用MongoDB的Shiny应用程序(使用mongolite)。应用程序加载并保存到数据库没有任何问题,但我试图找到一种方法来编辑MongoDB通过数据表(使用DT),当用户编辑或删除一行,他们可以按动作按钮来更新mongoDB。当我试图运行它时,我正在

  

"警告:错误:参数必须是bson或json。"

我有没有办法从DT编辑,将它转换为Mongo期待的Shiny应用程序的JSON?以下是代码。

library(shiny)
library(DT)
library(mongolite)

ui <- fluidPage(

  # Application title
  titlePanel("MongoTest"),

  # Sidebar
  sidebarLayout(
    sidebarPanel(
      actionButton("submit", "Submit"),
      actionButton("load","Load"),
      actionButton("update","update"),
      actionButton("deleteRows", "Delete Rows")
    ),

    #Main UI
    mainPanel(
      fluidPage(
        fluidRow(h2("Interactive Table", align="center")),
        tags$hr(),
        fluidRow(
              DT::dataTableOutput("Interactive_Table")
        )
      )
    )
  )
)


server = function(input, output, session){
  #Function that loads the information from the mongoDB
  loadData <- function() {
    # Connect to the database
    db = mongo(collection = "collectionhere",db ="SET", url = "mongodb://localhost:27017")
    # Read all the entries
    data <- db$find()

    return(data)

  }

  READ_IN_DATA=loadData()

  values <- reactiveValues(dfWorking = READ_IN_DATA)

  #Function that saves data to DB
  saveData <- function(data) {
    # Connect to the database
    db = mongo(collection = "collectionhere",db ="SET", url = "mongodb://localhost:27017")
    data <- as.data.frame(t(data))
    db$insert(data)
  }

  updateData = function(data){
      # Connect to the database
      db = mongo(collection = "collectionhere",db ="SET", url = "mongodb://localhost:27017")
      data <- as.data.frame(t(data))
      #subjects$update('{}', '{"$set":{"has_age": false}}', multiple = TRUE)
      db$update(data)
  }

  #Loading In the Data
  observeEvent(input$load, {
    loadData()
  })

  #Update the DB based off changes to the table
  observeEvent(input$update, {
    updated_df=as.data.frame(values$dfWorking)
    updateData(t(updated_df))
  })

  #Deleting Rows
  observeEvent(input$deleteRows,{
    if (!is.null(input$Interactive_Table_rows_selected)) {
      values$dfWorking <- values$dfWorking[-as.numeric(input$Interactive_Table_rows_selected),]
    }
  })

  #DT Table
  output$Interactive_Table = renderDataTable({
    datatable(values$dfWorking,editable=TRUE
    )
  })

}

# Run the application 
shinyApp(ui = ui, server = server)

0 个答案:

没有答案