Allow only one document in mongodb collection


November 2018


1.3k time


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 !");
        } else {
            console.log("Not skiping !!");
});, preferences) {
    if (err)
        console.log('error saving !!');
        console.log("Saved Preferences: " + preferences);

0 answers