Fetch data using mongoose and Express/Node Js - node.js

i am trying to fetch data from a MongoDB database using mongoose and express in Node js , i created the Model and successfully connected to database but the problem is i am getting an empty response while there already documents in the database collection .
Model class :
const mongoose = require("mongoose");
const RendezvousSchema = mongoose.Schema({
idpatient: {
type: String,
required: true
},
idmedecin: {
type: String,
required: true
},
});
module.exports = mongoose.model("Rendezvous", RendezvousSchema);
index.js :
const express = require("express");
const router = express.Router();
const Rendezvous = require("../model/RendezVous");
/* Get Rendez Vous By id */
/**
* #method - GET
* #description - Get Rendez vous Medecin
* #param - /user/GetRdvMedecin
*/
router.get("/GetRdvMedecin", async (req, res) => {
try {
const rdv = await Rendezvous.find();
res.json(rdv);
console.log('Fetched');
} catch (e) {
res.send({ message: "Error in Fetching rendez vous" });
}
});
/* Get Rendez Vous By id*/
module.exports = router;
this is the console.log :
Server Started at PORT 4000
Connected to DB !!
Fetched
Postman GET request on : 'http://localhost:4000/user/GetRdvMedecin'
Postman Response : ' [] '
document sample :
{
"_id":{
"$oid":"5e7396787b32a12e38a7aa7d"
},
"idpatient":"5e6ce11bc31de6132ca454a1",
"idmedecin":"5e5aa519190d8c2818a66a0a"
}
Hint : when i used another model ('user') it works fine and returns a response .

Your request .find() could return more than one object, I always return something like this:
router.get("/GetRdvMedecin", async (req, res) => {
let results;
try {
results = await Rendezvous.find();
} catch (e) {
res.send({ message: "Error in Fetching rendez vous" });
}
res.json({rendezvous: results.map(result => result.toObject({getters: true}) )});
});

Solved by adding the name of collection in the model
const mongoose = require("mongoose");
const RendezvousSchema = mongoose.Schema({
idpatient: {
type: String
},
idmedecin: {
type: String
}
},{
collection: 'Rendezvous'
});
// export model user with UserSchema
module.exports = mongoose.model("Rendezvous", RendezvousSchema);

Related

Cannot read property 'find' of undifined mongodb

I am starting to implement mongoose in a nodejs project. I have created a test record in a collection to test the CRUD operations from the back, I am trying to test the find() property of mongo but I am not sure how to do it.
This is my connection to mongoose:
const mongoose = require('mongoose');
const mongoURI: string = "mongodb://localhost:27017"
const mongoDB: string = "testdb"
export const setMongo = async() => {
try {
let mongodbURI: string = `${mongoURI}/${mongoDB}`
await mongoose.connect(mongodbURI);
console.log('conected DB')
} catch (error) {
console.log('error DB')
}
};
This is my Schema:
const mongoose = require('mongoose');
const companiesSchema = new mongoose.Schema ({
name: {
type: String,
required: true
},
phoneNumber: {
type: Number,
required: true,
unique: true
}
}, {
versionKey: false,
collection: 'companies'
});
module.exports = mongoose.model('Companies', companiesSchema);
This is my resposity.ts:
const companySchema = require("../../schemas/companies")
const db = companySchema.Companies
export class Repository {
public async getAll(): Promise<any> {
try {
console.log('getAll()')
const comp = await db.find({});
console.log(comp)
} catch (error) {
console.log(error)
}
}
}
This is the error it shows:
TypeError: Cannot read property 'find' of undefined
How should I create the connections or queries to mongo?
UPDATE
How can I get the total of the data with the find() method? Is it possible?
you just import your model in your controller and then you can use your query like:
const Companies = require("../../schemas/companies")
export class Repository {
public async getAll(): Promise<any> {
try {
console.log('getAll()')
const comp = await Companies.find({});
console.log(comp)
} catch (error) {
console.log(error)
}
}
}
and for get count of your result you can use .count() after your query to count your result :
const comp = await Companies.find({}).count();

how to set header for dat to be stored in database in nodeJS

I write post method to insert to mongodb:
const express = require("express");
const app=express();
const _route=require('./router/router.js')
require('dotenv').config();
require('./Database/config.js');
const port_=process.env.PORT|| 8080;
const product=require('./model/model.js');
const { db } = require("./model/model.js");
app.use('/insert',async(req,res)=>{
const newProduct=new product({
_id:57,
name:'GLX MAD',
description:'Newest iranian phone'
});
try{
await newProduct.save();
res.json(newProduct);
res.send('inserted')
}
catch(err){
res.send(err);
}
});
app.get('/:id',async(req,res)=>{
try{
const get=await product.findById(req.params.id);
res.json(get);
}
catch(err){
res.send(err);
}
});
app.get('/',async(req,res)=>{
try{
const get= await product.find();
res.json(get);
}
catch(err){
res.send(err);
}
})
app.listen(port_,'localhost',()=>{ console.log(`App run on port ${port_}`)});
the model is as follow:
const { default: mongoose } = require("mongoose");
const { stringify } = require("nodemon/lib/utils");
require('../Database/config');
const _product=mongoose.Schema({
_id:{
type:Number,
require:true
},
name:{
type:String,
require:true
},
description:{
type:String,
require:false
}
});
config of database is as follow:
require('dotenv').config();
const mongoose=require('mongoose');
const port_=process.env.PORT|| 8080;
const connectionString=`mongodb://localhost:27017/`;
mongoose.connect(connectionString,{
dbname:'Market',
useNewUrlParser:true,
useUnifiedTopology:true
},err=>{
err?console.log('Connection fail '+ err):console.log('Connect success.')
});
when I use post method e.g:localhost:3000/insert the data insert to database and then get following error and can not perform next operation such as get all data or get specific data:
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at new NodeError (node:internal/errors:371:5)
at processTicksAndRejections (node:internal/process/task_queues:96:5) {
code: 'ERR_HTTP_HEADERS_SENT'
how to set header for the data to be stored to database?
what is this header? why
Because of you return a json and you continue send a text
res.json(newProduct);
res.send('inserted')
just remove the second line res.send('inserted')
ref: http://expressjs.com/en/5x/api.html#res.send

How do I reference documents from other collection in express

I have 2 collections here >>course & author
I need to prepare my course schema in such a way that it references the author and at the post request I only need to put the id.I am using #joi13 This is what I have done so far.
course schema
const mongoose = require('mongoose')
const Joi = require('joi')
Joi.objectId= require('joi-objectid')(Joi)
// schema
const courseSchema = new mongoose.Schema({
...
author: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Author'
}
})
// the model
const Course = mongoose.model('Courses', courseSchema)
// validation
const courseValidation = (course) => {
const schema = {
...
authorId: Joi.objectId().required()
}
return Joi.validate(course, schema)
}
the course router
const {Course, validate} = require('../models/course')
const express = require('express')
const router = express.Router()
const {Author} = require('../models/author')
// post
router.post('/', async (req, res) => {
const {error} = validate(req.body)
if (error) return res.status(400).send(error.details[0].message)
const title = await Course.findOne({title : req.body.title})
if (title) return res.status(400).send('That user exists')
const author = await Author.find()
if (!author) return res.status(404).send('No such Author')
let course = new Course({
...
author: {
_id: author._id,
username: author.username
}
})
try {
course = await course.save()
res.send(course)
}
catch(er){
console.log(er)
}
})
The error
At line, const author = await Author.find() will return array of authors
while creating course at following lines of you are using author._id which will be undefined, So you have to find a specific Author using findOne (return a single author as object) or you have to use an indexed element of an author like author[0]._id
let course = new Course({
...
author: {
_id: author._id,
username: author.username
}
})

GraphQL Mongoose with MongoDB Atlas return empty array

I'm trying to connect MongoDB Atlas and mongoose but server always returns an empty array '[ ]'. When I load a mock data everything works (Mocked data and MongoDB Atlas have the same values)
I have connect to MongoDB Atlas, but can't get some data.
Controller:
const express = require('express')
const { ApolloServer } = require('apollo-server-express')
const { createServer } = require('http')
const mongoose = require('mongoose')
const typeDefs = require('./schema')
const resolvers = require('./resolvers')
const app = express()
const server = new ApolloServer({
typeDefs,
resolvers,
playground: {
endpoint: 'http://localhost:3000/graphql',
settings: {
'editor.theme': 'light'
}
}
})
server.applyMiddleware({ app })
const httpServer = createServer(app)
server.installSubscriptionHandlers(httpServer)
mongoose
.connect(`mongodb+srv://<username>:<password>#cluster0.brdqp.mongodb.net/${process.env.mongoDatabase}?retryWrites=true&w=majority`, { useNewUrlParser: true, useUnifiedTopology: true })
.then((res) => {
httpServer.listen(3000, () => {
console.log('connected!')
})
})
.catch((err) => {
console.error('Error while connecting to MongoDB', err);
})
Schema:
const { gql } = require('apollo-server-express')
const typeDefs = gql`
type Todo {
_id: String,
title: String,
description: String
status: String
date: String
}
type Query {
todos: [Todo]
}
`
module.exports = typeDefs
Resolvers:
const { Todo, Restaurant, Customer, Order } = require('./models')
const pubsub = require('./pubsub')
const resolvers = {
Query: {
todos(parent, args, context, info) {
return Todo.find()
.then(todo => {
return todo.map(r => ({ ...r._doc }))
})
.catch(err => {
console.error(err)
})
},
},
}
module.exports = resolvers
MongoDB Atlas collection: (Database name : node, collection name in DB : todo)
_id : 5c9bdb721c9d440000345d62
title : "question"
desctiption : "test test"
status: done
date: 1
But the server always returns [ ]
How???? Why&?

How to return the result of a mongodb pipeline by a get methodo?

I have a pipeline and its result I want to return it by an express method that is get or not i know if it is more advisable to send it by a socket
this is my file pipeline.js:
function getModel(model) {
model.aggregate([{
$group: {
_id: null,
"price": {
$sum: "$price",
}
}
}]).exec((e, d) => {
return JSON.stringify(d)
})
}
module.exports = getModel;
in the model.js file I'm going to call my pipeline.js file and therefore the function
model.js:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const getModel = require('./pipeline');
const mySchema = new Schema({
user: {
type: Schema.ObjectId,
ref: 'User'
},
namepet: String,
type_of_service: String,
characteristic_of_pet: String,
price: Number
});
const model = mongoose.model('Cites', mySchema);
here is the function-> getModel(model);
module.exports = model;
and it works for me as I want the problem is that the result I have to send it by a method get and I have no idea how to do it
How can I send the result indicating the red arrow of the image by a get method?
var express = require('express');
var app = express();
function getModel(model) {
model.aggregate([{
$group: {
_id: null,
"price": {
$sum: "$price",
}
}
}]).exec((e, d) => {
return JSON.stringify(d)
})
}
app.get('/', function(req, res) {
console.log('marhaba');
res.send(getModel( ** Model ** ))) //== > here call the getModel function
});
app.listen(3000, function() {
console.log("Working on port 3000");
});

Resources