Empty on collection - node.js

I have created database and have make one collection with the name staff there, I have put 3 data and it is showing on mongodb compass. But will try to fetch staff I got empty array. I am baby with this mongo db envirnment so I am unknow where did I get mess on my code.
Here, I have two files. one server.js which is main file and another is model file
server.js
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const Staff = require("./staff");
const dbname = "mydbname";
const dbpass = "mypassword";
const dbuser = "meuser";
mongoose.connect(
"mongodb+srv://"+dbuser+":"+dbpass+"#cluster0.ovjvl.mongodb.net/"+dbname+"?retryWrites=true&w=majority",
{ useNewUrlParser: true, useUnifiedTopology: true })
.then(() => console.warn("db connection done"))
.catch((error) => console.warn("DB Not Connect", error));
Staff.find({},(err,data)=>{
if(err) console.warn(err)
console.warn("Data :",data)
})
staff.js
const mongoose = require("mongoose");
let staffSchema = new mongoose.Schema({
_id : mongoose.Schema.Types.ObjectId,
name:String,
designation:String,
gender:String,
salary:mongoose.Schema.Types.Decimal128,
skills:mongoose.Schema.Types.Array})
module.exports = mongoose.model('staff',staffSchema)
While I run my app I got below ouput
db connection done
Data : []
But am expecting some data on array.
Note : For security reason, I have mention dbname,user & password is fake.

Related

Mongoose Schema in NodeJS UnhandledPromiseRejectionWarning: TypeError: Item is not a constructor

I'm building a cafe website with NodeJS, Express, and Mongo. I'm attempting to create a new cafe in one of my routes with a get request using a model I created. However, I keep getting an TypeError in my terminal stating that Cafe is not a constructor. I don't understand because I have defined the Schema in a separate file and I've included it in my app.js (routes file). Any feedback about this error is appreciated. I've included a few photos along with the code. Thank you in advance!
const path = require('path')
const mongoose = require('mongoose');
const Cafe = require("./models/cafe");
mongoose.connect('mongodb://localhost:27017/cafe-hopping', {
useNewURLParser: true,
useUnifiedTopology: true
})
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => {
console.log("Database connected");
});
const app = express()
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'))
app.get('/createcafe', async(req, res) => {
const cafes = new Cafe ({ name: 'Cueva Matera', description: "A cave like theme cafe"});
await cafes.save();
res.send(cafes)
})
*The following is the Schema (the file name is cafe.js)*
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CafeSchema = new Schema({
name: String,
price: String,
description: String,
location: String
});
module.export = mongoose.model('Cafe', CafeSchema);
[![app.js file. This is where I am keeping all of my routes][1]][1]
[![cafe.js file. This is where I create a new Schema for the database][2]][2]
[![This is the server error message I'm getting in my terminal every time I send the /createcafe get request][3]][3]
[1]: https://i.stack.imgur.com/mgTYg.png
[2]: https://i.stack.imgur.com/p9Ibx.png
[3]: https://i.stack.imgur.com/hFzzJ.png
The issue appears to be that you should be using
module.exports = mongoose.model('Cafe', CafeSchema);
Instead of module.export
Because of the misnamed property (export vs exports) the schema is not getting exported correctly, and Cafe is not a constructor.

How to create dynamic database in mongodb?

I'm learning MERN stack development, when I tried to connect the database through .env file, everything was working fine. Here is how my database string looks like:
MYDATABASE_String="mongodb+srv://avnish:avnish#cluster0.ojaf1.mongodb.net/registeredUsers?retryWrites=true&w=majority"
It is working fine when I'm trying to register users, they go under registeredUsers. But now, I'm also implementing blog portion, so when I publish a new blog, it goes under registeredUsers.
Now I want to know how to create a new database dynamically so that it goes to blogContent database and not in registeredUsers database.
Here is how my server.js looks like:
const express = require('express');
const mongoose = require('mongoose')
const app = express();
const dotenv = require('dotenv')
const routesURLs = require('./routes/routes')
const registerRouter = require('./routes/register')
const loginRouter = require('./routes/login')
const blogRouter = require('./routes/blog')
const cors = require('cors')
dotenv.config()
mongoose.connect(process.env.DATABASE_ACCESS,{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex:true
},()=>console.log(
'database connected successfully'),
)
app.use(express.json())
app.use(cors())
app.use('/',routesURLs)
app.use('/register',registerRouter)
app.use('/publish',blogRouter)
app.listen(4000, () => {
console.log(`Server started on port`);
});
This is my blog schema:
const mongoose = require('mongoose')
const blogModel = new mongoose.Schema({
title:{
type:String,
required:true,
},
category:{
type:String,
required:true,
},
slug:{
type:String,
required:true,
},
description:{
type:String,
},
content:{
type:String,
required:true
},
featuredImage:{
type:String,
},
publishedAt:{
type:Date,
default:Date.now
}
})
module.exports = mongoose.model('blog',blogModel)
And this is my blog.js
const { response, request } = require('express');
const express = require('express');
const router = require('express').Router();
const blogModel = require('../models/Blog')
router.post('/',async (req,res)=>{
const blogArticle = new blogModel({
title:req.body.title,
description:req.body.description,
category:"haha",
slug:"some-thing-here",
content:req.body.description,
})
blogArticle.save().then(data=>{
res.json({
data:data,
message:"Hurray all done"
})
}).catch(error=>{
res.json({
error:error,
message:"Lol! Nothing works"
})
})
})
module.exports = router;
Note
When I removed registeresUsers from the mydatabase string, every data goes to Test database.
While I don't agree that each type of document should get an entire database I will explain how to handle this case.
mongoose handles connections at the db level, While Mongodb allows a single connection to have multiple databases this is not the case here.
This means you'll have to create another mongoose instance and connect to the other database. This also means you can just do require('mongoose') anymore for the none default connection as this would be a different mongoose instance. I recommend creating a singleton that will serve the connection on demand to deal with this.
I will also add that mongoose is VERY inconvenient for this use case, I recommend you reconsider the actual need for another database.

Get existing document from MongoDB with Mongoose

I have an existing document on MongoDB atlas that I need to get in its entirety. When I try my current code I get a socket timeout, i.e. it keeps buffering.
There is only one document in my collection.
My theory is that the error is in my Mongoose Schema, but I don't know what to put there since I don't want any "filters", I want everything.
The name of the collection in Atlas is Playstation and the id of the document I want to get is: 5f5e2d281386efc27bb3ce45
const express = require('express')
const router = express.Router()
const Playstation = require('../models/playstation')
//Getting All
router.get('/', async (req, res) => {
try {
const playstations = await Playstation.findById("5f5e2d281386efc27bb3ce45")
res.json(playstations)
} catch (err) {
res.status(500).json({ message: err.message })
}
})
module.exports = router;
My schema & model:
const mongoose = require('mongoose')
const playstationSchema = new mongoose.Schema({
})
module.exports = mongoose.model('Playstation', playstationSchema)
I believe the problem is your mongoose schema. What you want is a schemaless collection, since you dont want to define the schema, and you want everything in the document, you can define the collection as schema-less, with strict:false option in your mongoose schema;
Try this:
const mongoose = require('mongoose')
const playstationSchema = new mongoose.Schema({
},{ strict : false })
module.exports = mongoose.model('Playstation', playstationSchema);
You can read more about this option on Mongoose Documentation

How to store a data in two different database in single node project with mongodb

I want to store a data in two different database in node.I tired but its not working.
// connect two databases
mongoose.connect(
keys.mongoURI
);
mongoose.connect(
keys.mongoURI1 //connectivity link
);
const express = require('express');
const app = express();
const ServerPortRouter = express.Router();
const ServerPort = require('../models/ServerPort');
ServerPortRouter.route('/add').post(function (req, res) {
const serverport = new ServerPort(req.body);
serverport.save()
.then(serverport => {
res.json('Server added successfully');
})
});
Data stored in single database, But I dont know to store this same data in two diffrent database
I am beginning to node I tired but I can't do this . Any help?
Try Creating separate models for each connection/database as below:
var conn = mongoose.createConnection('mongodb://localhost/testA');
var conn2 = mongoose.createConnection('mongodb://localhost/testB');
// stored in 'testA' database
var ModelA = conn.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in testA database' }
}));
// stored in 'testB' database
var ModelB = conn2.model('Model', new mongoose.Schema({
title : { type : String, default : 'model in testB database' }
}));

Mongoose MongoDB in Production

I'm having a really weird issue where Mongoose will not perform queries against collections outside of the Model definition file when NODE_ENV=production, even when connecting to localhost.
db/default.js
const mongoose = require('mongoose');
module.exports = {
connect(url) {
mongoose.connect(url);
}
};
app.js
const db = require('./db/default');
db.connect(config.get('mongoDB.uri'));
User.model.js
const mongoose = require('mongoose');
const schema = new mongoose.Schema({
// ...
});
const User = mongoose.model('User', schema);
module.exports = User;
test.js
// This file is required by a route
const User = require('./models/User.model');
User.find({})
.then(response => console.log(response))
.catch(err => console.log(err));
All of this works absolutely fine when NODE_ENV=dev, but as soon as NODE_ENV=production, the User.find({})... doesn't run. No errors, no success, it just doesn't run.
If I log the User = require('./models/User.model'), it is a Mongoose object.
If I run the User.find({})... code inside the User.model.js file whilst in production, that also works.
I am utterly befuddled as to why this does not work.

Resources