Answer the question
In order to leave comments, you need to log in
How to create an entry in the mongdb database?
Hello, I'm writing a REST API, but I can't seem to write a function to create a
Server.js entry:
// server.js
const express = require("express");
const MongoClient = require("mongodb").MongoClient;
const bodyParser = require("body-parser");
const colors = require("colors");
const db = require("./config/db");
const app = express();
const port = 8000;
app.use(bodyParser.urlencoded({ extended: true }));
MongoClient.connect(db.url, { useUnifiedTopology: true }, (err, database) => {
if (err) return console.log(err);
const maindb = database.db("maindb")
maindb.collection("posts")
console.log("server has been connected to database!".green)
require("./app/routes/index.js")(app, {});
app.listen(port, () => {
console.log("Server has been started on port... ".green + port);
});
});
const postRoutes = require("./post-routes.js");
module.exports = function(app, db, posts_collection) {
postRoutes(app, db, posts_collection);
// route handlers will be here...
};
module.exports = function(app, db, posts_collection){
app.post("/post", (req, res, posts_collection) => {
const post = { text: req.body.body, title: req.body.title };
posts_collection.create(post, function(err, res) {
if(err) {
return console.log(err)
}
console.log(result.ops)
client.close()
})
console.log(posts_collection)
res.send(post)
});
};
module.exports = {
url : "хотел украсть? а не!)"
}
server has been connected to database!
Server has been started on port... 8000
TypeError: posts_collection.create is not a function
at E:\code\js\REST_API\app\routes\post-routes.js:5:26
at Layer.handle [as handle_request] (E:\code\js\REST_API\node_modules\express\lib\router\layer.js:95:5)
at next (E:\code\js\REST_API\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (E:\code\js\REST_API\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (E:\code\js\REST_API\node_modules\express\lib\router\layer.js:95:5)
at E:\code\js\REST_API\node_modules\express\lib\router\index.js:281:22
at Function.process_params (E:\code\js\REST_API\node_modules\express\lib\router\index.js:335:12)
at next (E:\code\js\REST_API\node_modules\express\lib\router\index.js:275:10)
at E:\code\js\REST_API\node_modules\body-parser\lib\read.js:130:5
at invokeCallback (E:\code\js\REST_API\node_modules\raw-body\index.js:224:16)
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question