MongoDB /猫鼬填充

时间:2019-02-01 11:25:13

标签: node.js mongodb express mongoose

使用猫鼬“ Populate”-到目前为止,我无法成功获取“食物”模型来填充“用户”模型。

目标是能够为用户保存“食物”。

用户模型:

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    foods: [{ type: mongoose.Schema.Types.ObjectId}],
    easy: {type: Boolean, default: false}, 
});
UserSchema.plugin(passportLocalMongoose)
module.exports = mongoose.model("User", UserSchema);

食物模型:

var foodSchema = new mongoose.Schema({
   name:      { type: String, required: false, unique: true },
     author: {
        id: {
            type: mongoose.Schema.Types.ObjectId, 
            ref: "User",
        },
   }
});


module.exports = mongoose.model("Food", foodSchema);

获取路线

 router.get("/dashboard", function (req, res) {

        User.find({currentUser: req.user})
        .populate({path: 'foods'}).
        exec(function (err, foods) {
        if (err) return (err);

        console.log('The food is:', req.user.foods.name);

      });  
    });

发布路线:

router.post("/dashboard", function(req, res, next) {

    User.update({ id: req.session.passport.user }, {
    }, function(err, user) {
        if (err) return next(err);

        User.findById(req.user._id, function(err, user) {

            var newFood = new Food({
            name: req.body.currentBreakfast,
            image: 'test',
            });

            user.foods = newFood
            user.save();
            });
        });
        res.redirect('/dashboard');
});

3 个答案:

答案 0 :(得分:1)

您需要在用户架构中添加ref字段,以便在查询用户时填充食物。

var UserSchema = new mongoose.Schema({
   username: String,
   password: String,
   foods: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Food' }],
   easy: {type: Boolean, default: false}, 
});

答案 1 :(得分:1)

您可以使用此查询。

await User.find({currentUser: req.user}).populate('foods')

答案 2 :(得分:0)

尝试此操作将自动填充数据

var UserSchema = new mongoose.Schema({
  username: String,
  password: String,
  foods: [{ type: mongoose.Schema.Types.ObjectId,ref: 'Food'}}],
  easy: {type: Boolean, default: false}, 
});
UserSchema.pre('find', prepopulate)

function prepopulate(){
  return this.populate('foods')
}