Prem
Prem

Reputation: 5987

How does mongoose model connect with mongodb?

I have structured a user collection using mongoose.model().This model exist in seperate file called as model\user.js. The mongodb connection instance (using mongoose) exist in seperate file db\mongoose.js. Both of these files are imported into server.js to work with web application.

var express = require('express');
var bodyParser = require('body-parser');

var {mongoose} = require('./db/mongoose');
var {User} = require('./models/user');

var app = express();

app.use(bodyParser.json());

app.post('/todos', (req, res) => {
  var user = new User({
    text: req.body.text
  });

  user.save().then((doc) => {
    res.send(doc);
  }, (e) => {
    res.status(400).send(e);
  });
});

app.listen(3000, () => {
  console.log('Started on port 3000');
});

module.exports = {app};

The {mongoose} and {User} seems to be a separate entities and model\user.js didn't import ./db/mongoose.js as well . The user model being static content , how does user.save() connects with db and save the document?

Upvotes: 3

Views: 728

Answers (1)

Harshal Yeole
Harshal Yeole

Reputation: 4993

First of all let me tell you what is happening in your project.

in Mongoose file:

  • You have DB connection with Mongoose. Now Mongoose has your DB connection.

That is the reason it is imported in server.js file.

Secondly, in you model/user.js you have

  • Declared Schema using Mongoose.
  • user.save method.

When you use Mongoose here (or any DB related query), it points to your connected DB. Which does not require any explicit connection written in some file.

For more details read Mongoose Docs.

Hope I cleared your thoughts.

Upvotes: 2

Related Questions