6

I'm writing the backend for an application that needs to store some preferences.

I'm using the MEAN stack so the back end is express + mongodb. I'm using mongoose for this.

The database has to have a unique preference document that is present when the server starts and can only be updated. This document should not be overwritten neither (if I restart the server if the document is already created in the db: do not delete/modify it). But I can't figure out how to save the unique (default) document only once. It never goes into the pre.("save") callback.

I've done this:

var mongoose = require('mongoose'), Schema = mongoose.Schema;

var preferencesSchema = new Schema({
    /* preference schema */
});

var Preferences = mongoose.model('Preferences', preferencesSchema);

var default_prefs = new Preferences({
    /* default entry */
});

preferencesSchema.pre('save', function(next) {
    var self = this;
    /** NEVER GETS HERE **/

    Preferences.find({}, function(err, pref_documents) {

        if (pref_documents.length > 0) {
            console.log("Skiping save because a preference already exists !");
            next();
        } else {
            console.log("Not skiping !!");
            next();
        }
    });
});

default_prefs.save(function(err, preferences) {
    if (err)
        console.log('error saving !!');
    else
        console.log("Saved Preferences: " + preferences);
});
thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Sam
  • 341
  • 1
  • 4
  • 15
  • Why don't you just use a config file? – Philipp Mar 03 '15 at 13:05
  • 1
    Have you tried defining the `pre` action before defining your `Preferences` model? – JAM Mar 03 '15 at 13:10
  • @Philipp: any good resource on config files and more generally how to set up configuration ? – Sam Mar 03 '15 at 13:19
  • @Sam The best way to write a config depends on your and your users requirements. When you are in a Javascript context, you could just write your config as a JSON object in another javascript file. – Philipp Mar 03 '15 at 13:55
  • @Philipp: can you be more specific or give a link to an example, I can't find any on the web. You're talking about a mongodb config file right ? – Sam Mar 03 '15 at 14:02
  • 1
    @Sam No, I am talking about an application-specific config file with application-specific config settings for your application in an application-specific format. And that format can be whatever is most convenient for you to parse and edit. I recommended JSON because when you use Javascript you have a JSON parser build in and JSON is a format which is very human-readable and editable with a text editor. – Philipp Mar 03 '15 at 14:05
  • @Phillipp: Ah ! you mean an config file placed in the front end ? And never get preferences from the back-end ? – Sam Mar 03 '15 at 14:14

0 Answers0