需要帮助在mongoose中填充嵌套数组

时间:2017-06-08 23:28:50

标签: node.js mongoose

我正在努力使用mongoose填充嵌套数组。

我的食谱模型看起来像这样:

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
  },

});

我还有一个用户模型:

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
  }



});

每当用户制作新配方时,我希望该配方也存储在usersRecipe数组中。我尝试这样做的代码就是:

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


    });

我的代码无法正常工作。谁能向我解释我做错了什么?

1 个答案:

答案 0 :(得分:0)

这就是你在做什么...... 保存像

这样的食谱
{
        name: "hot chips",
        description: "some goods",
        steps: "2",
        ingredients: "",
        category: "chips",
        postedBy: "12312312312312"
}

然后用12312312312312 id搜索用户,有些用户喜欢这个

{
   name:"farshad",
   usersRecipes: []
} 

然后说给我填充usersRecipes ... 你弄错了吗? 你不要在你的用户文档中写出Recipe id。所以userRecipes总是空的......所以每次都没有得到任何用户的记录。

你有两个解决方案 1.当用户创建配方时,在usersRecipes中写出该配方ID ... 你可以创造......

recipe.save().then(function(res) {
   //update user document userrecipes array
});

OR 2.每次获得用户,在食谱集合中搜索具有该用户ID的食谱

Users.find({id:""}).exec(function(err, user) {
    if (err) throw err;
//fill userrecipes
    Recipes.find()....
});