Thursday, 8 June 2017

Need help populating nesting arrays in mongoose

I am struggling with populating nested arrays using mongoose.

I have a recipe model that looks something like this:

let recipeSchema = Schema({

  name: {
    type: String,
    required: true
  },

  description: {
    type: String,
  },

  steps: {
    type: String,
    required: true,
  },

  ingredients: [],

  reviewsArray: [{ type: Schema.Types.ObjectId, ref: 'Review' }],

  category: {
    type: String,
    required: true,
  },

  postedBy: [{type: Schema.Types.ObjectId, ref: 'User'}],

  numberOfRatings: {
    type: Number,
    default: 0
  },

  totalAddedRatings: {
      type: Number,
      default: 0
  },

  reviewAverage: {
      type: Number,
      default: undefined
  },

});

And I also have a User model:

let User = Schema({

  name: {
    type: String
  },

  // The passport plugin already inputs username and password into our Schema

  username: {
    type: String,
    unique: true,
    required: true
  },

   password: {
   type: String,
   required: true,
   minlength: 6
   },

   userId: {
     type: String,
     default: "Empty"
   },

   tokens: [{

    access: {
      type: String,
      required: true
    },

    token: {
      type: String,
      required: true
    }

  }],

  profilePic: {
    type: String
  },

  email: {
    type: String,
    unique: true,
    required: true,
    validate: {
      validator: (value) => {
        return validator.isEmail(value);
      },

      message: `{value} is not a valid email address.`
    }
  },

  admin: {
    type: Boolean,
      defualt: false
  },

  usersRecipes: [{ type: Schema.Types.ObjectId, ref: 'Recipe' }],

  usersReviews: [{ type: Schema.Types.ObjectId, ref: 'Review' }],

  usersFavouriteRecipes: {
    type: Array
  },

  usersLikedRecipes: {
    type: Array
  },

  chefKarma: {
    type: Number,
    defualt: 0
  }



});

Whenever the user makes a new recipe, I want that recipe to also be stored in the usersRecipe array. The code where I try to do that is this:

router.post('/addrecipe', (req, res, next) => {

    Recipe.create({
        name: req.body.name,
        description: req.body.description,
        steps: req.body.steps,
        ingredients: req.body.ingredients,
        category: req.body.category,
        postedBy: req.body.postedBy
    });


    User.find({_id: req.body.postedBy})
        .populate({
            path: 'usersRecipes',
            model: 'Recipe'
        })
        .exec(function(err, docs) {});


    });

My code is not working as I intended though. Can anyone explain to me what I am doing wrong?



via T-Dot1992

No comments:

Post a Comment