简体   繁体   中英

Problem with using the .save() in MongoDB

When i wanna save a user with this code:

const router = require("express").Router();
const User = require("../model/User");

//validate
const joi = require("@hapi/joi");

const schema = joi.object({
  name: joi.string().min(1).max(255).required(),
  email: joi.string().max(255).email().required(),
  password: joi.string().min(8).max(255).required(),
});

router.post("/register", async (request, respond) => {
  const { error } = schema.validate(request.body);
  if (error) return respond.status(400).send(error.details[0].message);
  const user = new User({
    name: request.body.name,
    email: request.body.email,
    password: request.body.password,
  });
  try {
    const savedUser = await user.save();
    respond.send(savedUser);
  } catch (err) {
    respond.status(500).send(err);
  }
});

module.exports = router;

it doesnt get any error but it also does not respond anything and does not save anything

I don't see any client connection in your code. Don't forget to connect to your mongoDB server and open your connection before processing any operation. Otherwise it won't have any effect.

var db = new Db('test', new Server('localhost', 27017));
// Establish connection to db
db.open((err, db) => {
   // Do what you want
});

See this example of saving a document in nodeJS: Save to MongoDB

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM