node.js - MongoDB/Mongoose 填充

标签 node.js mongodb express mongoose

使用 Mongoose“Populate” - 到目前为止,我无法成功获取“Food”模型来填充“User”模型。

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

用户模型:

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

最佳答案

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

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

关于node.js - MongoDB/Mongoose 填充,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54478537/

相关文章:

html - 在父目录中使用 javascript 不起作用

node.js - fs 模块函数使用的当前目录是什么?

node.js - 使用 mongodb 和 nodejs 解决 promise

javascript - 如何使用 Mongoose 删除对象内的子文档

MongoDB,选择嵌套数组字段

javascript - 如何使用 express router 正确调用 passport.js 函数?

javascript - 使用 Angular 和 UI-Router 进行访问控制。调用堆栈大小错误且未到达 Express 身份验证路由

javascript - 我怎样才能获得在discord.js中作为消息发布的值(value)

node.js - Node CLI 工具评估字符串

javascript - 如何将JS对象传递给redis中它自己的事件参数 - 连接事件上的sentinel