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.