2

I have a problem with saving user's data to MongoDB; save function saves only user's id and also when I log user before trying to save it, I get only id too. When I log req.body I get all the data.

I guess the problem is somewhere in instancing userSchema.

const userSchema = require('../models/user.model');
var User = mongoose.model('user', userSchema);

Here is my code:

module.exports.register = (req, res, next) => {
var user = new User(req.body);
user.name = req.body.name;
user.email = req.body.email;
user.username = req.body.username;
user.password = req.body.password;

user.save((err, doc) => {
    if (!err) {
        res.send(doc);
    }
    else {
        console.log(err);
        if (err.code == 11000) {
            res.status(422).send(['Duplicate email adrress found.']);
        }
        else
            return next(err);
    }
  });
}

Here is my console.log(req.body)

    {
      name: 'name',
      email: 'mail@mail',
      username: 'username123',
      password: '12345'
    }

And this is console.log('document' + doc)

document: { _id: 5ea3237a48b41b3cc08bfe1f, __v: 0 }
Dragana
  • 51
  • 1
  • 6
  • can you show your user schema – Shubh Apr 24 '20 at 17:21
  • Sure, here it is: const userSchema = new Schema({ name: { type: String, required: [true, 'This field can\'t be empty'] }, email: { type: String, required: [true, 'This field can\'t be empty'] }, username: { type: String, required: [true, 'This field can\'t be empty'] }, password: { type: String, required: [true, 'This field can\'t be empty'] }, saltSecret: String }); – Dragana Apr 24 '20 at 17:23
  • Please see the answer . – Shubh Apr 24 '20 at 17:24

1 Answers1

1

The issue as you mention in the question is with the use model import

Can you add this at the end of the (user.model) model file: module.exports = User = mongoose.model("User", userSchema); and import in controller as const User = require("../models/user.model");.

Just want to bring the attention to two different behavior of console log with "," and "+" . Please check it. And I don't think you need following 4 lines as well:

user.name = req.body.name;
user.email = req.body.email;
user.username = req.body.username;
user.password = req.body.password;

let user = {"_id":"a", "name":"ABCD"};
  
console.log("doc"+ user)

console.log("doc", user)
halfer
  • 18,701
  • 13
  • 79
  • 158
Nayan
  • 617
  • 5
  • 14
  • With or without those 4 lines, when I log user all I get is this: { _id: 5ea32b754c939026ec997f64 } – Dragana Apr 24 '20 at 18:11
  • Can you check using any tool like MongoDB Compass to check the actual document in the DB? – Nayan Apr 24 '20 at 18:13
  • Only id is saved to the database – Dragana Apr 24 '20 at 18:27
  • 1
    Can you add this at the end of the (user.model) model file :=> module.exports = User = mongoose.model("User", userSchema); and import in controller as const User = require("../models/user.model"); – Nayan Apr 24 '20 at 18:39