Mr.Smithyyy
Mr.Smithyyy

Reputation: 1329

Use mongodb in nuxt

I am trying to use MongoDB for long term and complex storage that Vuex isn't suited for.

I have MongoDB installed and running and I installed the mongoose package.

In my plugins folder, I have a create a script that initializes the module and exports it:

plugins/mongoose.js

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/users', { useNewUrlParser: true });

export default({ app }, inject) => {

    inject('mongoose', mongoose);

}

and then in my nuxt.config.js, I declare the module and set it as server side only.

nuxt.config.js

...
plugins: [
    { src: '~/plugins/mongoose.js', mode: 'server' },
],
...

and then finally, in one of my pages I try to access it in a method.

pages/users.vue

<template>
    <button @click="addUser('joe')">Joe</button>
</template>

<script>
    export default {
        methods: {
            addUser(name) {
                console.log(this.$mongoose);
            }
        }
    }
</script>

and when I click the button in the console I get cannot stringify a function change and then cannot stringify a function name. I can't tell if this is working but I can't use any properties of the mongoose object.

There doesn't seem to be much structured information on this topic even though it seems like it would be fairly common.

Upvotes: 4

Views: 11801

Answers (2)

Jasper Kennis
Jasper Kennis

Reputation: 3062

You could create your own serverMiddleware, and then call that in your asyncData. Simplified, I have the following:

// nuxt.config.js
const bodyParser = require('body-parser')

export default {
  ...,
  serverMiddleware: [
    bodyParser.json(),
    { path: '/db-api', handler: '~/api/db-connection' },
  ],
}

in db-connection you can add something like:

import {
  getOneDocument,
} from '../utils/db-helper'

export default async function (req, res, next) {
  const doc = await getOneDocument('my-one-and-only-collection', req.body)

  res.end(JSON.stringify(doc))
}

and then in asyncData you can do something like:

async asyncData (context: any) {
  const reqq = await axios.post(
    `${url}/db-api`,
    {
      'sys.id': '2J2a1nQhmTYbHML2si8gmW'
    }
  )
  return {
      thatOneAndOnlyRecord: reqq.data,
  }
}

You will need to make sure that any complex querying happens inside your middleware as well since you are making a network request for each query to mongo.

Upvotes: 6

Aldarund
Aldarund

Reputation: 17621

You cant do it like this. Nuxt is frontend. So the code will be executed on client in their browsers. Your event will be executed in browser when user click on button. So you cant access mongoose there. mongoose dont work in browser, only in node.

So you need to have backend that will do your mongoose stuff and send\recieve data from your nuxt there using REST or GraphQL or whatever

Upvotes: -4

Related Questions