It does not return anything back (hang state) and i see in console
{ _id: 5f05d1527de7984a2c998385, name: 'alexa', age: 12 }. I tried both method promise and callback but still same. Can you guess what could be the issue?
const express = require('express');
const app = express();
const mongoose = require('mongoose');
app.use(express.json());
const TestModel = mongoose.model(
'test',
new mongoose.Schema({
name: {
type: String,
required: true,
},
age: {
type: Number,
required: true,
},
}),
);
app.post('/test', async (req, res, next) => {
const testUser = req.body;
const Test = new TestModel(testUser);
console.log(Test);
/* Test.save(function (err, doc) {
if (err) {
return res.json({ message: 'something went wrong' });
}
res.json(testUser);
}); */
await Test.save();
res.json(testUser);
});
app.listen(4000, () => {
console.log('playground is up');
});
Related
I've read through some of the answers similar to this question and have struggled to see how they would apply to mine. The issue I am having is that when I try to retrieve any data from my MongoDB database, it returns an empty array. I've already set my network access to 0.0.0.0/0, and it says it successfully connects to my DB when I run my backend. I was hoping someone might be able to lend a hand. The GitHub for this file is https://github.com/dessygil/des-personal-site-backend
Here is my index.js file
const express = require("express");
const app = express();
const dotenv = require('dotenv').config();
const mongoose = require("mongoose")
const jobsRoute = require("./routes/jobs");
mongoose.set('strictQuery', false);
app.use(express.json());
mongoose.connect(process.env.MONGO_URL, {
useNewUrlParser: true,
useUnifiedTopology: true,
}).then(console.log("Connected to MongoDB")).catch((err) => {
console.log(err)
});
app.use("/", jobsRoute);
app.listen(process.env.PORT || 5000, () => {
console.log("Connected to port 5000");
});
My Jobs model
const mongoose = require("mongoose");
const JobSchema = new mongoose.Schema(
{
startDate: {
type: Date,
required: true,
},
endDate: {
type: Date,
required: false,
},
company: {
type: String,
required: true,
unique: false,
},
title: {
type: String,
required: true,
unique: true,
},
url: {
type: String,
required: true,
},
duties: {
type: [String],
required: true,
},
},
{ timestamps: true },
);
module.exports = mongoose.model("Job", JobSchema)
My route file
const router = require("express").Router();
const Job = require("../models/Job");
//Create new post
router.post("/", async (req, res) => {
const newJob = new Job(req.body);
try {
const savedJob = await newJob.save();
res.status(200).json(savedJob);
} catch (err) {
res.status(500).json(err);
};
});
//Update post
router.put("/:id", async (req, res) => {
try {
const updatedJob = await Job.findByIdAndUpdate(
req.params.id,
{
$set: req.body,
},
{ new: true }
);
res.status(200).json(updatedJob);
} catch (err) {
res.status(500).json(err);
}
});
//Delete post
router.delete("/:id", async (req, res) => {
try {
const job = await Job.findById(req.params.id);
await job.delete()
res.status(200).json("Post had been deleted");
} catch (err) {
res.status(500).json(err);
}
});
//Get post
router.get("/:id", async (req, res) => {
try {
const job = await Job.findById(req.params.id);
res.status(200).json(job);
} catch (err) {
res.status(500).json(err);
}
});
//Get all posts
router.get("/", async (req, res) => {
try {
allJobs = await Job.find();
console.log(allJobs,"you are here");
res.status(200).json(allJobs);
} catch (err) {
res.status(500).json(err);
}
});
module.exports = router;
The structure of my db
What is returned on postman (hosted on heroku but also doesn't work when I run locally and returns the same results
The type of data stored in jobs there is 3 documents that should show up
the program doesnt show errors but when i run it on browse all i get is 2 brackets
here is my code
const express = require("express");
const app = express();
const mongoose = require("mongoose");
const CompteModel = require('./models/Compte.js');
mongoose.connect('mongodb://localhost:27017/école');
app.get("/getCompte", (req, res) => {
CompteModel.find({}, (err, result) => {
if (err) {
res.json(err);
} else {
res.json(result);
}
});
});
app.listen(3001, () => {
console.log("Hello");
});
Here is the schema of the collection "Compte".
const mongoose = require("mongoose");
const CompteSchema = new mongoose.Schema({ login: { type: String, required: true, }, password: { type: String, required: true,
},
});
const CompteModel = mongoose.model("Compte",CompteSchema); module.exports = CompteModel;
I'm new to NodeJS,I'm just trying to create a restfull API, but when I try to execute the code by running (npm run dev),it's throwing an error.There are many questions like this one, but no answer could figure out what is wrong in my code.
the error is : app.use() requires a middleware function
this is my index.js
const express = require("express");
const app = express()
const departmentRouter = require("../src/routes/department")
app.use(express.json())
app.use(departmentRouter)
const port = process.env.PORT || 3000;//local machine port 3000
app.listen(port, () => (`Server running on local machine port ${port} 🔥`));
this is the model :
const mongoose = require("mongoose");
const validator = require('validator')
const Department = mongoose.model('Department', {
name: {
type: String,
required: true,
}
,
email: {
type: String,
required: true,
trim: true,
lowercase: true,
validate(value) {
if (!validator.isEmail(value)) {
throw new Error('Invalid email!')
}
}
}
,
createdBy: {
type: String,
default: 'SYS_ADMIN'
}
,
updatedBy: {
type: String,
default: 'SYS_ADMIN'
}
,
createdAt: {
type: Date
// ,
// default: Date.getDate()
}
,
updatedAt: {
type: Date
// ,
// default: Date.getDate()
},
isDeleted: {
type: Boolean,
default: false
}
})
module.exports = Department
this is routes file (department.js)
const express = require("express");
const router = express.Router();
const Department = require("../models/department")
router.get("/v1/departments", async (req, res) => {
try {
const departments = await Department.find({ isDeleted: false })
if (!departments) {
return res.status(404).send()
}
res.status(200).send()
} catch (error) {
res.status(500).send(error)
}
});
router.get("/v1/department/:id", async (req, res) => {
//test if the department exist => by id
const _id = req.params._id
try {
const depatment = await Department.findByid(_id, { isDeleted: false })
if (!depatment) {
return res.status(404).send()
}
res.status(200).send(depatment)
} catch (error) {
res.status(500).send(error)
}
});
router.post("/v1/department", async (req, res) => {
try {
const department = new Department(req.body) //this param is for testing the post methode by sending request from postman
await department.save()
} catch (error) {
res.status(500).send(error)
}
});
router.put("/v1/department/:id", async (req, res) => {
//especially useful when testing the put method using postman
const updates = Object.keys(req.body)
const allowedUpdates = ['name', 'email']
const isValideOperations = updates.every((update) => allowedUpdates.includes(update))
if (!isValideOperations) {
return res.status(400).send({ error: 'Invalid updates' })
}
try {
const _id = req.params.id
const department = await Department.findByIdAndUpdate(_id)
if (!department) {
return res.status(404).send()
}
res.send(department)
} catch (error) {
res.status(500).send(error)
}
})
//Safe delete by updating the field isDeleted to true
router.delete('/v1/department/:id', async (req, res) => {
try {
const _id = req.params.id
const department = await Department.findByIdAndUpdate(_id, { isDeleted: true })
if (!department) {
return res.status(400).send()
}
res.status(200).send(department)
} catch (error) {
res.status(500).send(error)
}
})
In the department.js file, you need to export the router:
module.exports = router
I created a small project with node+express+mongodb
This is where i call the create user:
const express = require("express");
const User = require("../models/user");
const router = express.Router();
router.post("/register", async (req, res) => {
try {
const user = await User.create(req.body);
return res.send({ user });
} catch (e) {
return res.status(400).send({ error: "Registration failed" });
}
});
module.exports = app => app.use("/auth", router);
and here is the Schema for the user:
const mongoose = require("mongoose");
const UserSchema = new mongoose.Schema({
name: {
type: String,
require: true
},
email: {
type: String,
require: true,
unique: true,
lowercase: true
},
password: {
type: String,
require: true,
select: false
},
createdAt: {
type: Date,
default: Date.now
}
});
const User = mongoose.model("User", UserSchema);
module.exports = User;
But when o make the resquest, it nevers get a response, it waits forever. And when o take out the await from the request, it gets an empty response { "user": {}}
I'm kind lost looking the mongoose documentation (the ideia is to make a simple rest api, i'm used with python, but looking to learn node)
You have to create a new user from User Model as follows:
const express = require("express");
const User = require("../models/user");
const router = express.Router();
router.post("/register", async (req, res) => {
try {
var user = new User(request.body);
var result = await user.create();
return res.send({ result });
} catch (e) {
return res.status(400).send({ error: "Registration failed" });
}
});
module.exports = app => app.use("/auth", router);
Here's my Schema:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const PostsSchema = new Schema({
userId: String,
postId: String,
title: String,
description: String,
tags: { many: String, where: String, what: String },
date: { type: Date, default: Date.now },
}, { collection : 'posts'});
const Posts = mongoose.model('Post', PostsSchema);
module.exports = Posts;
Here's my route with the query:
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const Posts = require('../models/Posts');
router.get('/', (req, res, next) => {
const refreshOrLoadMore = params.refreshOrLoadMore || '';
if (refreshOrLoadMore === 'loadMore') {
console.log('1');
Posts.find({}).sort({date:-1}).limit(10, (err, data) => {
if(err) {
console.log('2');
res.send(err);
} else {
console.log('3');
res.json(data);
}
});
}
});
The if statement returns true and the first console.log is triggered. But after that none of the other console.logs are triggered and just nothing happens. No data is being send and no error is being send.
So my guess is, that i did something wrong with the Schema, but i did it just as i did my other ones and they do work.
Can someone point out where i went wrong?
Thanks in advance!
Try this
if (refreshOrLoadMore === 'loadMore') {
console.log('1');
Posts.find({}).sort({date:-1}).limit(10)
.exec((err, data) => {
if(err) {
console.log('2');
res.send(err);
} else {
console.log('3');
res.json(data);
}
});
}