简体   繁体   中英

How do i use mongodb with electron?

I'm currently building a desktop application using Electron and MongoDB. The objective of this application is to collect and store information of various customers in the local scope of the application (not on a server). I've done some research into MongoDB with node.js; however I haven't found a way to use it in Electron.

This is an electron app for MongoDB management, you can check the code as an example on how to use mongodb and electron.

https://github.com/officert/mongotron

Basically you can use mongodb as you would normally use in node.js in the Main process and then communicate with Renderer process through the ipc module .

For example:

Renderer process

<html>
  <head></head>
  <body>
    <script>
    const ipc = require('electron').ipcRenderer;
    const informationBtn = document.getElementById('information-dialog')

    informationBtn.addEventListener('click', function (event) {
      ipc.send('create-user')
    })
    </script>
  </body>
<html>

Main process

const ipc = require('electron').ipcMain
const mongo = require('some-mongo-module')

ipc.on('create-user', function (event) {
  /* MONGODB CODE */
})

I would recommend you to use the get started app that you can find in http://electron.atom.io/

I am using Electron + React + Typescript and I had to import mongoose like so:

const mongoose = window.require("mongoose");
// then you can connect to it like so:
mongoose.connect("mongodb://localhost:27017/test");

This will get rid of the error:

TypeError: mongoose.connect is not a function

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