How to query imported json using Mongoose - javascript

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}`));

Related

Can't get my api to work in Postman, POST returns 404 . its a vue frontend and express backend

I'm following this tutorial and I'm stuck at the end. getting 404's in postman when using POST with this URL http://localhost:5050/api/projects its been 3 days any one know what I'm doing wrong?
server.js
const express = require("express");
const app = express();
const PORT = 5050;
// Connect to the database
require("./src/server/database/connection");
const bodyParser = require("body-parser");
const cors = require("cors");
var corsOptions = {
origin: "http://localhost:5051"
};
app.use(cors(corsOptions));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json());
// parse requests of content-type - application/x-www-form-urlencoded
app.use(express.urlencoded({ extended: true }));
// simple route
app.get("/", (req, res) => {
res.json({ message: "Code Wire Server." });
});
require("./src/server/routes/routes")(app);
app.listen(PORT, () => {
console.log(`Server is listening at http://localhost:${PORT}`);
});
connection.js
How to connect to the database
const db = require("../model/index.js");
db.mongoose
.connect(db.url, {
useNewUrlParser: true,
useUnifiedTopology: true
})
.then(() => {
console.log("Connected to the database!");
})
.catch(err => {
console.log("Cannot connect to the database!", err);
process.exit();
});
index.js
const dbConfig = require("../config/db.config.js");
const mongoose = require("mongoose");
mongoose.Promise = global.Promise;
const db = {};
db.mongoose = mongoose;
db.url = dbConfig.url;
db.project = require("./projects_db.js")(mongoose);
module.exports = db;
db.config.js
module.exports = {
url: "mongodb://127.0.0.1:27017/code-wire-db"
}
projects_db.js
A database schema for my project I'm working on
module.exports = mongoose => {
var schema = mongoose.Schema({
project_title: String,
description: String,
} );
schema.method("toJSON", function() {
// eslint-disable-next-line no-unused-vars
const { __v, _id, ...object } = this.toObject();
object.id = _id;
return object;
});
const projectsDB = mongoose.model("projectsDB", schema);
return projectsDB;
projects_controller.js
const db = require("../model/index");
const project = db.project;
// Create and Save a new project
exports.create = (req, res) => {
// Validate request
if (!req.body.title) {
res.status(400).send({ message: "Content can not be empty!" });
return;
}
// Create a project
const Project = new project({
project_title: req.body.project_title,
description: req.body.description
});
// Save project in the database
Project
.save(Project)
.then(data => {
res.send(data);
})
.catch(err => {
res.status(500).send({
message:
err.message || "Some error occurred while creating the Project."
});
});
};
routes.js
module.exports = app => {
const projects = require("../controller/projects_controller.js");
var router = require("express").Router();
// Create a new project
router.post("/", projects.create);
app.use('/api/projects', router);
};
I found the problem.
[![problem][1]][1]
See that return symbol, I found out 4 days later that means there is 2 lines or more. Meaning postman was sending 2 lines instead of one. With no error message
[1]: https://i.stack.imgur.com/VVlha.jpg

Postman Returning Empty when using GET request

I am working on a RESTful API using mongodb, js, express and postman to test it. I am trying to connect to my cloud atlas mongodb cluster and retrieve all the information. However, when testing it on postman, it returns empty: []
I can connect to the database just fine and I have 3 documents in my collection. The name of the database is mobile_phone_store and the collection is called personal_information
here is my server.js
const express = require("express");
const mongoose = require("mongoose");
const infoRoute = require("./app/routes/db.routes.js");
const app = express();
app.use(express.json());
mongoose.connect(
"mongodb+srv://*************************/mobile_phone_store?retryWrites=true&w=majority", {
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true
}
);
app.use(infoRoute);
app.listen(3000, () => {
console.log("Server is running...");
});
here is my db.model.js
const mongoose = require('mongoose');
// create a mongoose schema for a quotation
const PersonalInfoSchema = mongoose.Schema({
customerID: String,
Title: String,
Fname: String,
Lname: String,
mobile: String,
email: String
}, {
timestamps: true
});
// export the model to our app
const personal_information = mongoose.model("personal_information", PersonalInfoSchema);
module.exports = personal_information;
here is my db.routes
const express = require("express");
const Model = require("../models/db.model");
const app = express();
app.get("/personal_informations", async(request, response) => {
const infos = await Model.find({});
try {
response.send(infos);
} catch (error) {
response.status(500).send(error);
}
});
module.exports = app;
In postman I am using the url http://localhost:3000/personal_informations. Any Ideas? I have been searching for an solution for a while now and Im not finding anything
The issue might be with the MongoDB connection.
Try this to listen when the connect resolves:
mongoose
.connect(
'mongodb+srv://*************************/mobile_phone_store?retryWrites=true&w=majority',
{
useNewUrlParser: true,
useFindAndModify: false,
useUnifiedTopology: true,
}
)
.then(() => {
app.listen(3000, () => {
console.log('Server is running...');
});
})
.catch((err) => console.log(err));

How can I get the data of particular collection of mongodb?

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.

MongoDB Returns Empty Error Object when Making POST Request

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 ;)

Cant connect to specific database and collection inside mongoDB Atlas Cluster

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

Categories

Resources