Reputation: 121
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 }
Upvotes: 2
Views: 560
Reputation: 658
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)
Upvotes: 1