简体   繁体   中英

How should in right way connecting MongoDB in Nodejs?

Hello i am new in Nodejs & MongoDb. I created controllers for API where i want create new items in MongoDB , edit, search items. Now i am connecting to MongoDB via mongoose in main file server.js . But i need that i can create, edit in editor.js . I tried to export mongoose module, but it was unsuccessfull. How i can do this in right way?

my structure

在此处输入图片说明

`editor.js` file - where i want have access to database
const models = require('./../models');
const client = require('./../../server');
const mongoose = require('mongoose');
let db;
// const db = client.db('todo');
module.exports = {
    getNewsById: async (req, res) => {
        console.log(req.params);
        // console.log(req);
        res.send({oK: 'ok'});
    },
    createNews: async (req, res) => {
        const newItem = req.body;
        newItem['publishedAt'] = Date.now();
        console.log('HERE', client);
        console.log('HERE2', client.db.collection('test').insertOne({
            item: 'canvas',
            qty: 100,
            tags: ['cotton'],
            size: { h: 28, w: 35.5, uom: 'cm' }
            }));
        }
    }

In editor.js after importing mongoose, you can simply load your model using -

const db = require('mongoose');
const testModel = db.model('test');

And then you can call your db queries similar to -

testModel.insert(...);
testModel.find();

Once you have built your model using mongoose, it is available in the application. You just need to get it through mongoose.

If you need more help, you can refer to my sample project at https://github.com/kravigupta/nodejs-express-mongo-auth

For every new developer who is learning node.js, the first thing they go with the MongoDB connection with the node.js.

I will suggest you keep the MongoDB connection URL, username and password in a separate file say it db.config.js file and then import that file into you server.js or app.js or main file of your node.js and then connect mongo with the try catch block to handle the error. IF you need to learn in more details then you can refer to this link .

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