Mongoose model.find() function not work from second connection - mongodb

In my database I have two collections admins and users.I'm using them from different express apps.Both apps connected to the same database.Now I need to fetch all users list from admin app. Here is my User model.
const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
const config = require('../configs/config');
const uuid = require('uuid/v4');
// User Schema
const UserSchema = mongoose.Schema ({
email: {type: String,required: true,unique:true},
password: {type: String,required: true,unique:true},
created_at:{type:Date,default:Date.now()},
updated_token:{type:String,default:null,unique:true},
deleted:{type:Boolean,default:false},
activation_Token:{type:String,default:null},
isActive:{type:Boolean,default:false}
});
const User = module.exports = mongoose.model('User', UserSchema);
module.exports.getUserById = function(id, callback) {
User.findById(id, callback);
}
module.exports.getUserByEmail = function(email, callback) {
const query = {email}
User.findOne(query, callback);
}
In my admin app I use Uesr.find() function and it doesn't make any sense.Models are in different paths and I dont think that its can bring troubles.Also I'm using nginx web server for proxy-passing.

Related

i keep get TypeError x is not constructor

i have model with mongoose
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const CampgroundSchema = new Schema({
title:String,
price:Number,
description:String,
location:String
});
module.export = mongoose.model('Campground', CampgroundSchema)
i save it
i import to variable
const Campground = require('campground');
i want to get data on browser so :
app.get('/makecampground', async (req, res) => {
const camp = new Campground ({title:"Corn Field", description:"We can BBQ there"})
await camp.save();
res.send(camp)
})
but when i go to browser 'localhost3000/makecampground' my terminal just say
Campground is not a constructor
so i want to that Campground data show on my database

MERN stack : Express api returning empty data , but the data is already present in mongodb

I am new to the MERN stack, and I have been trying to access my collections in MongoDB.
Here is the code for the router, view bookings:
/*This is router file*/
var mongoose = require('mongoose');
const express = require('express');
const bodyParser = require('body-parser')
let book = require('../models/BookTravel');
const router = require('express').Router()
router.use(express.json())
router.route('/').get((req, res) => {
// Company.aggregate({companyId})
book.find()
.then((result) => {
console.log(result)
return res.status(200).json(result)
})
})
module.exports = router;
/*
* this is for model
*/
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const TravelSchema = new Schema({
firstname:{
type: String,
required: true
},
bookingId:{
type: String,
required: true
},
lastname:{
type: String,
required: true
},
startcity:{
type: String,
required: true
}
})
const travel = mongoose.model('travel', TravelSchema)
module.exports = travel;
////in app.js file
const viewBookings = require('./routes/viewBookings');
app.use('/viewBookings', viewBookings)
The postman is also giving empty result.
What am I missing out ? Is it not possible to access the already existing collection with this method ?
You are missing some code in the router file.
for example! If you want to get data from a database
you can simply use like below this
.......
router.get("/",async (req,res)=>
{
try{
const result = await book.find();
res.status(200).json({"message" : result})
}
catch(error)
{
console.log(error)
}
})
......

How to use Mongoose find query in express router?

I am trying to use Mongoose find query to get the complete list of documents held in my mongodb. However for some reason, the query stopped working and hasn't worked since. I believe all my code is correct, and its not giving me any error messages either.
Routes\image.js
const router = require('express').Router();
let imageModel = require('../Models/image');
router.get('/collection',(req,res) => {
imageModel.find({},(err,data) => {
if(err) {
res.status(500).json({msg:"Cant find collection",err})
} else {
res.send(data);
}
})
})
module.exports = router;
Models \ image
let mongoose = require('mongoose');
const Schema = mongoose.Schema;
let imageSchema = new Schema({
name:String,
desc:String,
imgUrl:String
});
let model = new mongoose.model('Image',imageSchema);
module.exports = model;
index.js
const express = require('express');
const app = express();
const cors = require("cors");
const PORT = process.env.PORT || 5001;
// Routes
const imageRoute = require('./Routes/image');
app.use(express.json());
app.use(cors());
require('dotenv').config()
require('./db.config');
app.use('/image',imageRoute);
app.get('/',(req,res) => {
res.send('First Route!')
})
app.listen(PORT,() => {
console.log(`listening on port ${PORT}`)
})

mongoose not fetching data

I am trying to fetch all users from a MongoDB database. However for some reason recently the request did not fetch anything.
Here is the code in which I try to fetch the data:
app.get('/api/allusers', (req, res) => {
Employee.find()
.then(rettrievedData => {
res.json(rettrievedData)
});
});
Here is the mongoose model:
const mongoose = require('mongoose');
const employeeSchema = mongoose.Schema({
name: { type: String },
surName: { type: String },
mail: { type: String },
phone: { type: String },
});
module.exports = mongoose.model('Employee', employeeSchema, 'employee.employees');
Here is the code for connecting to Mongo
mongoose.connect("mongodb+srv://Kiril:xxxxxxxxxxxxx#cluster0-owdfy.mongodb.net/employee?retryWrites=true&w=majority")
.then(() => {
console.log("Connected")
})
Also I have checked that there is data in the database, but for some reason the Employee.find() does not retrieve anything. What can be reason?
Thanks in advance.
why you are adding 'employee.employyes' when you creating your model
try to export the model without it
module.exports = mongoose.model('Employee', employeeSchema)
or better
exports.Employee = mongoose.model('Employee', employeeSchema)
and require it where you want to use it
const Employee = require('path to the schema file')

Can't save to mongoDB's database

While sending a post request i written the following code :
var email = req.body.email ;
var newDetails = { email: email };
Details.create(newDetails);
console.log(newDetails);
while sending the request. The console.log shows me the correct details,
However in the mongo shell the only collection that exist is "details" and it's empty .
That's the Mongoose Schema:
var mongoose = require("mongoose");
var DetailsSchema = mongoose.Schema({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
I'm using NodeJS.
Thanks in advance.
Your Mongoose Model should be like
const mongoose = require("mongoose");
const Scheme = mongoose.Schema;
const DetailsSchema = new Scheme({
email: String
});
module.exports = mongoose.model("Details", DetailsSchema);
Node js Code should be like
var detailsModel = require('../model/Details.js');//path of mongoose model
var detailsData = new detailsModel();
detailsData.email = req.body.email;
detailsData.save(function (err, savedJob) {
if (err) {
return res.send(err);
} else {
return res.send(savedJob);
}
});
To save data in mongoDB's Database
You can use this way
var detailsData = new detailsModel();
detailsData.save()
.then(business => {
res.status(200).json({'Details': 'newDetails added successfully'});
})
.catch(err => {
res.status(400).send("unable to save to database");
});
With this, you can also handle error easily.