In the below cole, in 4th line, Messages is my collection name of mongodb which I created on other file. And if I find the data of this collection then no error is occuring.
But when I am writing other collection name of mongodb which I created manually on mongodb website then it is giving error.
import express from "express";
import mongoose from "mongoose";
import Pusher from "pusher";
import Messages from "./messages.js";
import dynamicModel from "./messagesRoom.js";
import cors from "cors";
// app configuration
const app = express();
const port = process.env.PORT || 9000;
//middleware
app.use(express.json());
app.use(cors());
// DB Configuration
const url = "mongodb+srv://suraj_bisht_99:zoe6B82AZjaLXgw7#cluster0.zp9dc.mongodb.net/Whatsapp_MERN";
mongoose.connect(url, {useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> console.log('mongoDB is connected'))
.then(err => console.log(err));
// API routes
app.get("/", (req, res) => {
res.status(200).send("Hello World");
})
app.get("/messages/sync", async (req, res) => {
await other__collection.find( (err, data) => {
if(err){
console.log(err);
res.status(500).send(err);
}else{
res.status(200).send(data);
}
})
})
app.post("/messages/new", async (req, res) => {
try{
const newMessage = new Messages(req.body);
const newMessageCreated = await newMessage.save();
res.status(201).send(newMessageCreated);
}
catch(err){
res.status(400).send(err);
}
});
// listening part
app.listen(port, () => console.log(`listening on port number ${port}`));
My question is how can I get the data of other collections of mongoDB in the same way as I am getting with the collection which I made on other file
This is my Message collection.
import mongoose from "mongoose";
const messageSchema = mongoose.Schema( {
message: String,
name: String,
timestamp: String,
received: Boolean,
});
const messageContent = mongoose.model('messageContent', messageSchema);
export default messageContent;
Since you are using mongoose, you have to create a Schema and a Model for each collection, and then you can query MongoDB with that Model.
So, create a Schema and a Model for that other collection like you did with messageContent and use that Model when you query DB.
Related
I am having trouble being able to insert data into my collection, I'm not even sure I'm doing it correctly so I apologize for the vague request but maybe my code will help you see what my intention is. The gist of it is I'm trying to make a separate file for my schema/collection and then call it from another file and insert data and call other functions etc.
file1.js file:
require('dotenv').config()
const User = require('./assets/js/data')
const bodyParser = require("body-parser");
const mongoose = require('mongoose');
mongoose.connect(process.env.url, { useNewUrlParser: true })
.then(() => {
console.log('Connected to MongoDB server');
})
// 1. Import the express module
const express = require('express');
// 2. Create an instance of the express application
const app = express();
app.set('views', './static/html');
app.set('view engine', 'ejs');
app.use(express.static('assets'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// 3. Define the HTTP request handlers
app.get('/', (req, res) => {
res.render('main')
});
app.get('/login', (req, res) => {
res.render('login')
});
app.post('/login', (req, res) => {
console.log(req.body.number);
})
app.listen(3000, (err) => {
console.log("running server on port")
if (err) {
return console.log(err);
}
})
data.js
const mongoose = require('mongoose');
const userData = new mongoose.Schema({
phoneNumber: String,
})
const User = mongoose.model('User', userData);
module.exports(
User,
)
This line has the error.
// error
module.exports(
User,
)
module.exports is not a function.
module.exports = User
// or
module.exports = { User }
if you do the first one, then required should be like this,
const User = require('./assets/js/data')
otherwise
const { User } = require('./assets/js/data')
More about module.exports
The Data.js is correct but the way your controller works is I think the issue. If you use "const User = require('./assets/js/data')" you can use your selected variable User and then connect find, create, etc. you can use this as a reference. https://blog.logrocket.com/mern-stack-tutorial/
Adding collections manually is easy but adding it dynamically giving me unexpected answer.
I am getting a collection name from frontend to backend using promt and axios but when I am doing
const variable_from_frontEnd = mongoose.model(variable_from_frontEnd, Schema);
it is not adding any collections.
import express from "express";
import mongoose from "mongoose";
import Messages from "./messages.js";
import cors from "cors";
// app configuration
const app = express();
const port = process.env.PORT || 9000;
const pusher = new Pusher({
appId: "1183689",
key: "c9fa659fc6b359a23989",
secret: "9da56a5db535e10c7d95",
cluster: "eu",
useTLS: true
});
//middleware
app.use(express.json());
app.use(cors());
// DB Configuration
const url = "mongodb+srv://suraj_bisht_99:zoe6B82AZjaLXgw7#cluster0.zp9dc.mongodb.net/Whatsapp_MERN?retryWrites=true&w=majority";
mongoose.connect(url, {useCreateIndex: true, useNewUrlParser: true, useUnifiedTopology: true})
.then(()=> console.log('mongoDB is connected'))
.then(err => console.log(err));
const groupSchema = mongoose.Schema( {
message: String,
name: String,
timestamp: String,
received: Boolean,
});
// API routes
app.get("/", (req, res) => {
res.status(200).send("Hello World");
})
app.get("/messages/sync", async (req, res) => {
await Messages.find( (err, data) => {
if(err){
console.log(err);
res.status(500).send(err);
}else{
res.status(200).send(data);
}
})
})
app.post("/messages/new", async (req, res) => {
try{
const newMessage = new personalGroup(req.body);
const newMessageCreated = await newMessage.save();
res.status(201).send(newMessageCreated);
}
catch(err){
res.status(400).send(err);
}
});
// route for creating new collection in mongoDB
app.post("/room/new", async (req, res) => {
try{
let groupName = req.body.room;
groupName = mongoose.model(groupName, groupSchema);
if(!groupName){
console.log("error is occured");
}else{
console.log(groupName);
}
}
catch(err){
res.status(400).send(err);
}
})
// listening part
app.listen(port, () => console.log(`listening on port number ${port}`));
Let's say I have type a collection name "studyGroup" from frontend then
console is giving me
Model { studyGroup }
Can someone help me why it is happening and how can I add collections manually.
I'm currently learning about APIs. I'm using Dev Ed's video on a RESTful MERN API. I set up my routes and I could successfully connect to my MongoDB database. However, when attempting to call save() on a post to the DB, I was returned my error message, a JSON object with a message containing the err, but my err object was completely empty.
posts.js:
const express = require('express');
const router = express.Router();
const Post = require('../models/Post');
router.get('/', (req, res) => {
res.send('We are on /posts!');
});
router.post('/', (req, res) => {
const post = new Post({
title: req.body.title,
desc: req.body.desc,
});
post.save()
.then(data => {
res.json(data);
})
.catch(err => {
res.json({ message: err });
});
});
module.exports = router;
app.js:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
const PORT = 8080;
app.use(bodyParser.json());
// Import Routes ------------------------
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
// ROUTES --------------------------------
app.get('/', (req, res) => {
res.send('We are home!');
});
mongoose.connect(
process.env.DB_CONN,
{ useNewUrlParser: true },
() => {
console.log('Succesfully connected to DB!')
});
app.listen(PORT);
Post.js (schema):
const mongoose = require('mongoose');
const PostSchema = mongoose.Schema({
title: {
type: String,
required: true,
},
desc: {
type: String,
required: true,
},
date: {
type: Date,
default: Date.now,
}
});
module.exports = mongoose.model('Posts', PostSchema);
My POST request and response (Postman):
In my code, I am attempting to send the new Post to my DB, but instead I get an error, an empty one. I either need to figure out how to view my error correctly (so that's it's not empty) or the larger problem: why my POST request is failing.
Again, I am learning about APIs, this is my very first time writing one. If there's anything I missed (like other code that you would need) or if there's something I should be doing differently, please, let me know! Thank you in advance!
use status when you want to use res like this:
for success result
res.status(200).json(data);
for .catch
res.status(500).json({ message: err });
but I prefer use async/await with try/cacth like this:
router.post('/', async(req, res) => {
const post = new Post({
title: req.body.title,
desc: req.body.desc,
});
try {
let data = await post.save()
res.status(200).json(data)
} catch (error) {
res.status(500).json({ message: error});
}
});
check the documentation of promises in mongnoos
check the connection of mongoose like this:
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
require('dotenv/config');
const app = express();
const PORT = 8080;
app.use(bodyParser.json());
// Import Routes ------------------------
const postsRoute = require('./routes/posts');
app.use('/posts', postsRoute);
// ROUTES --------------------------------
app.get('/', (req, res) => {
res.send('We are home!');
});
runMongoose()
app.listen(PORT);
async function runMongoose(){
try {
await mongoose.connect(
process.env.DB_CONN,
{ useNewUrlParser: true }
);
console.log("mongodb is OK");
} catch (error) {
console.log("mongodb Warning", error);
}
}
if Succesfully connected to DB! printed mongoose connection is OK
the problem is that you added
{ useNewUrlParser: true }
remove that and it's gonna work fine ;)
I am creating a MERN stack application and have chosen to use mongoose to communicate with MongoDB Atlas. But MongoDB Atlas uses clusters with databases inside which again has collections. I cant find any documentation for how to connect to a specific database and collection.
this is my current code:
File with the schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
User: {
fisrtname: String,
lastname: String,
email: String,
password: String,
},
Todos: [
{
title: String,
completed: Boolean,
id: Schema.Types.ObjectId,
},
],
});
module.exports = mongoose.model('User', userSchema, 'todosCollection');
Main server file
const express = require('express');
const path = require('path');
const mongoose = require('mongoose');
const dbConfig = require('./database/db');
const app = express();
const PORT = process.env.PORT || 8080;
// Connecting to MongoDB database
mongoose.Promise = global.Promise;
mongoose
.connect(dbConfig.db, {
useNewUrlParser: true,
})
.then(
() => console.log('Database Sucsessfully connected!'),
err => console.error('Could not connect to database: ' + err)
);
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
app.use('/api/todos', require('./routes/api/todos'));
app.listen(PORT, () => console.log(`Server is running on port ${PORT}`));
And the function who searches MongoDB
! This is a snippet from another file but the rest is unimportant to the question.
const userSchema = require('../../database/models/User');
router.get('/', (req, res) => {
userSchema.find((err, data) => {
if (err) {
res.staus(500).json({ msg: 'Did not found database data' });
} else {
res.json(data);
}
});
});
Once you have connected with your Atlas MongoDB cluster - you can treat it the same as any other MongoDB connection. See my answer on how to correctly connect to an Atlas cluster: https://stackoverflow.com/a/61480485/8322220.
However, you also seem to be having an issue querying your data, but it is hard to help without the relevant code.
However, in your 3rd snippet, you are querying User - but I think your User schema is not correct.
I suggest that you separate Todos into its own Schema and export separately to User i.e:
module.exports = mongoose.model('Todo', todoSchema)
By passing dbname as options parameter you can specify the database,
check out the link for clarity.
https://mongoosejs.com/docs/connections.html#options
I've uploaded a json file to MongoDB Atlas cluster (using mongoimport) and now I'm trying to display the data to localhost using express and mongoose.
I've gotten to a point where I can connect to the cluster but I'm struggling in fetching and displaying the data. Below is the code I have thus far. I'd like to query the database via Nodejs using mongoose as I do on the command line with Mongo shell. What am I missing here?
const express = require("express");
const mongoose = require("mongoose");
const app = express();
// DB config using Mongo Atlas
const uri = require("./config/keys").mongoURI;
// // Connect to Mongo
mongoose
.connect(uri, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected..."))
.catch(err => console.log(err));
// #route GET
app.get("/", (req, res) => res.send(db.restaurants.find()));
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
First, initialize a model which Mongoose needs to query data. Since you've imported the data, you don't necessarily have to structure your schema.
// restaurants.js
const mongoose = require('mongoose');
const RestaurantsSchema = new mongoose.Schema({});
module.exports = mongoose.model('Restaurants', RestaurantsSchema)
Then, import the schema 'Restaurants' into your main driver file and specify your query by chaining filters like so:
// main.js
const express = require("express");
const mongoose = require("mongoose");
const Restaurants = require("./restaurants");
const app = express();
// DB config using Mongo Atlas
const uri = require("./config/keys").mongoURI;
// Connect to Mongo
mongoose
.connect(uri, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected..."))
.catch(err => console.log(err));
// #route GET
app.get("/", (req, res) => {
Restaurants.find()
.where("filter1").gt(200)
.where("filter2").equals("$$$")
.where("filter3").nin(["Coffee"])
.limit(100)
.sort("sort1")
.select("column1 column2 column3")
.then(restaurants => res.json(restaurants))
.catch(err => res.status(404).json({ success: false }));
});
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));
You should fill in the applicable values for "filter", "sort", "column", "gt", "equals", "limit", and "nin".
I am not sure if this is the only record of that type of json in your data base. But If you want to send if follwing a get request you first need to get the document.
// #route GET
app.get("/", (req, res) => res.send(db.restaurants.find()));
// may be something like
app.get('/', (req, res) => {
mongooseModel.find({query}, (err, result) => {
res.send(result);
});
})
Depending on what mongoose.model defenition you have and how you would like to find it you could use find (return an array) findById (return single document) or findOne and a query.
here an example how to create you model:
//restaurant.js
const mongoose = require('mongoose');
const RestaurantSchema = new mongoose.Schema({
name: { type: String, required: true },
address: { type: String, required: true },
description:{ type: String, required: true }
//just you add how you need your schema
});
module.exports = mongoose.model('Restaurant', RestaurantSchema);
and here your updated code
const express = require("express");
const mongoose = require("mongoose");
const Restaurant = require("./restaurant.js");
const app = express();
// DB config using Mongo Atlas
const uri = require("./config/keys").mongoURI;
// // Connect to Mongo
mongoose
.connect(uri, { useNewUrlParser: true })
.then(() => console.log("MongoDB Connected..."))
.catch(err => console.log(err));
// #route GET
app.get("/", (req, res) => {
Restaurant.find({}, (err, docs) => {
res.send(docs);
});
);
const port = process.env.PORT || 5000;
app.listen(port, () => console.log(`Server started on port ${port}`));