MongoDB/猫鼬填充 [英] MongoDB/Mongoose Populate

查看:67
本文介绍了MongoDB/猫鼬填充的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用猫鼬"填充"-到目前为止,我无法成功获得食物"模型填充用户"模型.

Working with Mongoose "Populate" - So far I'm unable to successfully get the "Food" model to populate the "User" model.

目标是能够为用户保存食物".

用户模型:

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

推荐答案

您可以使用此查询.

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

这篇关于MongoDB/猫鼬填充的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆