Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 344
Mr.Smithyyy Avatar asked Oct 28 '25 05:10

Mr.Smithyyy


1 Answers

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.

like image 195
Jasper Kennis Avatar answered Oct 30 '25 00:10

Jasper Kennis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!