Torstein Eika Amsrud
Torstein Eika Amsrud

Reputation: 13

Mongoose pre-save hook fires, but does not persist data

I am encountering a problem where my Mongoose pre.save() hook is firing, but the attribute does not get saved to the database. I have been searching for a long time without finding an answer.I found this thread, and the behaviour I am experiencing is very similiar, but OP's problem is related to the context of this, whereas I seem to have a different problem.

Here is my models.js:

'use strict';

const mongoose = require("mongoose");
const slugify = require("slugify");

let Schema = mongoose.Schema;

let BlogPostSchema = new Schema({
    title: {
        type: String,
        required: true
    },
    createdAt: {type: Date, default: Date.now},
    updatedAt: {type: Date, default: Date.now},
    author: String,
    post: {
        type: String,
        required: true    
    }
});

BlogPostSchema.pre('save', function(next) {
    this.slug = slugify(this.title);
    console.log(this.slug);
    next();
});

// Passed to templates to generate url with slug.
BlogPostSchema.virtual("url").get(function() {
    console.log(this.slug);
    console.log(this.id);
    return this.slug + "/" + this.id;
});

BlogPostSchema.set("toObject", {getters: true});

let BlogPost = mongoose.model("BlogPost", BlogPostSchema);

module.exports.BlogPost = BlogPost;

And here is the relevant lines in the router file index.js:

const express = require('express');
const router = express.Router();
const BlogPost = require("../models").BlogPost;

// Route for accepting new blog post
router.post("/new-blog-post", (req, res, next) => {
    let blogPost = new BlogPost(req.body);
    blogPost.save((err, blogPost) => {
        if(err) return next(err);
        res.status(201);
        res.json(blogPost);
    });
});

I am able to save the blog post to the database, and my console.log's correctly prints out the slug to the console. However, the this.slug in the pre-save hook does not get persisted in the database.

Can anybody see what the problem is here? Thank you so much in advance.

Upvotes: 1

Views: 660

Answers (1)

Kayvan Mazaheri
Kayvan Mazaheri

Reputation: 2597

Mongoose will act according to the schema you defined.
Currently, your schema does not contain s filed named slug.

You should add a slug field to your schema.

Changing your current schema to something like this should work:

let BlogPostSchema = new Schema({
    slug: String,    
    title: {
        type: String,
        required: true
    },
    createdAt: {type: Date, default: Date.now},
    updatedAt: {type: Date, default: Date.now},
    author: String,
    post: {
        type: String,
        required: true    
    }
});

Upvotes: 1

Related Questions