Allow only one document in mongodb collection

Refresh

November 2018

Views

1.3k time

4

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);
});
Sam

0 answers