Home > Software design >  Validation Error in mongoDB while making a reference to another Schema?
Validation Error in mongoDB while making a reference to another Schema?

Time:01-03

I have created a blog schema in mongo which makes reference to the user schema. However, when I try to save the blog in MongoDB I get the following error: -

CUrrrent post user:  new ObjectId("61d28db34c78f60375189033")
User validation failed: passwordHash: Path `passwordHash` is required., name: Path `name` is required., username: Path `username` is required.

I am sending this via JSON

{
        "title": "Best Copywriting formulas!",
        "author": "Copywriters Inc.",
        "url": "https://buffer.com/resources/copywriting-formulas/",
        "likes": 420
    }

I am unable to decode why I am getting this validation error when I am adding nothing new to the User schema.

Here is my main router code: -

blogRouter.post('/', async (request, response) => {
    const blog = new Blog(request.body)

    if (blog.author === undefined || blog.title === undefined)
        return response.status(400).json({
            error: "name or title missing!"
        })

    //temporary get the first user from the Users db
    const userDB = await User.find({});
    //Get the first available user in db
    const currentUser = userDB[0]._id;

    console.log('CUrrrent post user: ', currentUser);

    const newBlog = new User({
        title: request.body.title,
        author: request.body.author,
        url: request.body.url,
        likes: request.body.likes || 0,
        user: currentUser
    })

    try {
        const newEntry = await newBlog.save()
        response.status(200).json(newEntry);
    } catch (error) {
        logger.error(error.message);
    }
})

My Blog Schema: -

const blogSchema = new mongoose.Schema({
  title: String,
  author: String,
  url: String,
  likes: {
    type: Number,
    default: 0
  },
  user: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User'
  }
})

blogSchema.set('toJSON', {
  transform: (document, returnedObject) => {
    returnedObject.id = returnedObject._id.toString()
    delete returnedObject._id
    delete returnedObject.__v
  }
})

module.exports = mongoose.model('Blog', blogSchema)

Here is my user Schema: -

var uniqueValidator = require('mongoose-unique-validator');

const userSchema = new mongoose.Schema({
    username: {
        type: String,
        required: true,
        minLength: 3,
        unique: true
    },
    name: {
        type: String,
        required: true
    },
    passwordHash: {
        type: String,
        required: true
    }
})

userSchema.plugin(uniqueValidator, {message: 'username already taken. {VALUE} not available.'});

userSchema.set('toJSON', {
    transform: (document, returnedObject) => {
        returnedObject.id = returnedObject._id.toString()
        delete returnedObject._id
        delete returnedObject.__v
        delete returnedObject.passwordHash
    }
})

const User = mongoose.model('User', userSchema);
module.exports = User

CodePudding user response:

You should change your model name when creating a new Blog document:

  const newBlog = new Blog({
    title: request.body.title,
    author: request.body.author,
    url: request.body.url,
    likes: request.body.likes || 0,
    user: currentUser,
  });

Also, a good practice would be to check if there are any users in the database before retrieving the first one. This to avoid possible index out of bounds exceptions:

const userDB = await User.find({});
if (userDB.length > 0) {
    const currentUser = userDB[0]._id;
    ...
  • Related