Add Data to MongoDB Models At Different Times

I have a pretty good understanding of mongdoDB with mongoose, but this one aspect of it has been confusing me for a while now. I have a user.js model with a username, password, etc (all the basic user stuff). This data is added when a user registers for an account. But each user also has more data linked to it that IS NOT created or added at the time of registering.

This is my model:

// User Schema
const UserSchema = new Schema({

    // PERSONAL USER INFO
    username: {
        type: String,
        index: true
    },
    email: {
        type: String
    },
    password: {
        type: String
    },

    // INSTAGRAM ACCOUNT INFORMATION
    ig_username: {
        type: String
    },
    ig_password: {
        type: String
    },
    story_price: {
        type: Number
    },
    fullpost_price: {
        type: Number
    },
    halfpost_price: {
        type: Number
    },
    leads: [{
        title: { type: String }
    }]
});

// EXPORTS
const User = module.exports = mongoose.model('user', UserSchema);

All the field except "leads" are created at the time of registering. But I want to fill the Leads field using another form. I've tried the .update(), .save(), $set, $push, and all kinds of methods, but I cannot get it to work.

Most solutions that I have found use var user = new User({...}) to create a new user and then use .save() after adding the additional data. But this seems wrong since the user has already been created and I am just trying to add data to an additional field.

I think I'm just glossing over something basic, but if there is a way to do this I would be glad to hear it. Thanks!

1 answer

  • answered 2018-02-13 02:18 Grégory NEUT

    I would create a sub-schema for leads

    // Create a sub-schema for leads
    const leadsSubSchema = new Schema({
      title: {
        type: String,
      },
    });
    
    // Create a schema for user
    const UserSchema = new Schema({
      username: {
        type: String,
        index: true
      },
    
      // ...
    
      leads: [leadsSubSchema]
    });
    
    // EXPORTS
    const User = module.exports = mongoose.model('user', UserSchema);
    

    Then for the update

    User.update({
      _id: user_id,
    }, {
      $push: {
        leads: lead_to_add,
      },
    });