【问题标题】:MongoDB/Mongoose PopulateMongoDB/Mongoose 填充
【发布时间】:2019-06-25 23:22:27
【问题描述】:

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

【问题讨论】:

    标签: node.js mongodb express mongoose


    【解决方案1】:

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

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

    【讨论】:

    • 谢谢! User.foods 现在给出一个类似 ["5c543cc8ec51174b58d047d0"] 的对象 - 我如何让它显示食物名称?
    • 在UserSchema中添加ref后,可以在find查询中使用populate()
    【解决方案2】:

    您可以使用此查询。

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

    【讨论】:

    • 谢谢! :) user.foods.name 未定义。 user.foods 是一个对象。有什么想法吗?
    • 更新我的答案。请检查
    • 试一试。 user.foods.name 未定义。 user.foods 是一个对象。
    【解决方案3】:

    试试这个它会自动填充数据

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

    【讨论】:

    • 自动填充与问题有什么关系? ://
    猜你喜欢
    • 2020-10-14
    • 2021-03-03
    • 2020-02-10
    • 2019-10-19
    • 2016-08-06
    • 2021-04-19
    • 2019-11-24
    • 1970-01-01
    • 2012-01-22
    相关资源
    最近更新 更多