0

i want to write data over my Express server with the ´post´ methode to the mongoDB.

i use mongoose to connect to my mongodb with the code:

const mongoose=require("mongoose")

const LogInSchema=new mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    password:{
        type:String,
        required:true
    }
})

const user=new mongoose.model("UserList", LogInSchema)

module.exports=user

Im also connect to my mongodb with my external script:

const mongoose=require("mongoose")

function connectdb() {
    
mongoose.connect("mongodb://localhost:27017/User")
.then(()=>{
    console.log("connected to db");
})
.catch(()=>{
    console.log("There was a problem");
})}

module.exports = {connectdb};

Now i want to write with a post methode the data to the mongodb:

  app.post("/signup",async (req,res)=>{
    const data={
        name:req.body.name,
        password:req.body.password,
    }
    console.log(data)
    await user.insertMany([data])
})

so, in the mongoShell i can see, that the collection User is created, and i can also see in the console th log output from my input.

If i want to look in the collection over the mongosh with db.User.find(), there is no data in the collection User.

Is this th right way to write the data to mongodb? await user.insertMany([data])

i have also tried it with this endpoint:

  app.post("/signup",async (req,res)=>{
    const data = new user(req.body);
    console.log(data)
      try {
    await data.save();
    res.send(data);
  } catch (error) {
    res.status(500).send(error);
  }
})

in the Terminal, i can see the data values. The data also rendered on the Browser. But if i show in the database over mongosh in the terminal, the database is empty.

coldstone
  • 17
  • 5
  • Yo defined your model schema name as `UserList` `mongoose.model("UserList",...)`. You can't see the data in `user` collection it should be in `userlists` collection. Checke `userlists` exists and there has some data. – PRATHEESH PC Jun 25 '23 at 04:35
  • `mongoose.connect("mongodb://localhost:27017/userlist")` this creates the collection userlist, but the collection is empty. Im correct to check the collection woth the command db.userlist.find() in mongosh? – coldstone Jun 25 '23 at 08:56
  • Try `await user.insertOne(data)`. You're only inserting one record, so use `insertOne` instead of `insertMany` – Rob Jun 25 '23 at 09:37
  • You can also check the result of the insert like this `const result = await user.insertOne(data)`, `console.log(result)` – Rob Jun 25 '23 at 09:39
  • with `await user.insertOne(data)` i get this error => `TypeError: user.insertOne is not a function.` And with `const result = await user.insertOne(data)`, `console.log(result)` i can see the data in the console => `{ name: 'exampleuser', password: 'examplepassword' }`. – coldstone Jun 25 '23 at 10:08
  • Sorry, I was thinking of the command for Mongo shell, not mongoose. Try `user.create(data)` – Rob Jun 25 '23 at 17:56
  • with `user.create(data)` its also the same problem. The Collection is empty. – coldstone Jun 25 '23 at 19:08
  • @PRATHEESH you are correct from the beginning. I dont recognize the "s" at the end of `userlists`. I can see the data in the collection `userlists`. But i wonder why mongoose creates a collection with `userlists` and not `userlist` which is defined in `const user=new mongoose.model("userlist", LogInSchema)` ??? – coldstone Jun 25 '23 at 22:34
  • See here...https://stackoverflow.com/questions/10547118/why-does-mongoose-always-add-an-s-to-the-end-of-my-collection-name – PRATHEESH PC Jun 26 '23 at 02:57

1 Answers1

0

Maybe i do a failura in other place in my code, so here the complete code.

my app.js:

var express = require("express");
var fs = require("fs");
var https = require("https");
var bodyParser = require("body-parser");
var database=require('./script/connectdb')
var path = require("path");
const user = require("./mongodb");


const app = express();
const port = 80;

//create https server
https
  .createServer(
    {
      key: fs.readFileSync("ssl/privkey.pem"),
      cert: fs.readFileSync("ssl/cert.pem"),
    },
      app
  )
  .listen(443, () => {
    console.log('https server is running on port 443')
  });

// Connect to database
database.connectdb();

//static elements
app.use(express.static(__dirname + '/dist'));
app.use(bodyParser.urlencoded({ extended: true }));

app.set('view engine', 'ejs');

//CRUD
app.get('/', (req, res) => {
  res.send("Hallo")
 res.sendFile(__dirname, 'index.html');
 console.log('funktioniert');
})

app.post("/signup",async (req,res)=>{
  const data={
      name:req.body.name,
      password:req.body.password,
  }
  console.log(data)
  const result = await user.insertOne(data)
  console.log(result)
})

app.post("/login",async (req,res)=>{
const userlist = new user();
userlist.name = req.body.name;
userlist.password = req.body.password;
await userlist.save(function (err, data) {
  if (err) {
      console.log(error);
  }
  else {
      res.send("Data inserted");
  }
});
})

my connectdb:

const mongoose=require("mongoose")

function connectdb() {
    
mongoose.connect("mongodb://localhost:27017/userlist")
.then(()=>{
    console.log("Mit mongodb erfolgreich verbunden!");
})
.catch(()=>{
    console.log("Es konnte keine Verbindung hergestellt werden");
})}

module.exports = {connectdb};

and mongoose schema (mongodb.js

const mongoose=require("mongoose")

const LogInSchema=new mongoose.Schema({
    name:{
        type:String,
        required:true
    },
    password:{
        type:String,
        required:true
    }
})

const user=new mongoose.model("userList", LogInSchema)

module.exports=user
coldstone
  • 17
  • 5