尝试填充我的用户模型并出现类型错误

时间:2018-10-17 18:20:58

标签: javascript node.js mongodb express mongoose

在我的程序中,我想用称为组的模型填充索引页面。以前,我只显示了数据库中存在的所有组,但现在我只想显示已登录用户所关联的组。

以下是这些型号: 组模型

var mongoose = require("mongoose");

var groupSchema = new mongoose.Schema({

    name: String,
    thumbnail: String,
    description: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    },
    inviteCode: String,
    images: [
        {
            type: mongoose.Schema.Types.ObjectId,
            ref: "Image"

        }
    ],
    users: [
        {
           type: mongoose.Schema.Types.ObjectId,
           ref: "User"
        }
    ] });

module.exports = mongoose.model("Group", groupSchema);

用户模型

var mongoose = require("mongoose");
var passportLocalMongoose = require("passport-local-mongoose");

var UserSchema = new mongoose.Schema({
    username: String,
    password: String,
    groups: 
        [
            {
                type: mongoose.Schema.Types.ObjectId, //referencing model by id
                ref: "Group" //name of the model
            }
        ],
    images: 
        [
            {
                type: mongoose.Schema.Types.ObjectId, //referencing model by id
                ref: "Image" //name of the model
            }
        ]
});

UserSchema.plugin(passportLocalMongoose); //add in local mongoose methods to user

module.exports = mongoose.model("User", UserSchema);

我的索引路线:

//Index Route
router.get("/", middleware.isLoggedIn, function(req, res){
    var user = req.user;
    user.populate("groups").exec(function(err, allGroups){ 
       if(err){
           console.log(err);
       } else {
           res.render("groups/show", {groups: allGroups});
           console.log(allGroups);
       }
   });
});

这是我得到的错误:

  

TypeError:user.populate(...)。exec不是函数

我不确定为什么不能在用户模型中使用populate方法,有人可以向我解释一种替代方法以实现所需结果的原因。谢谢。

1 个答案:

答案 0 :(得分:1)

我认为问题在于req.user不是架构,因此.populate并不是该变量在其对象原型中携带的方法。因此,终端会告诉您这不是功能。

您必须在索引路由中要求这样的User模式:

const User = require("./models/user");

然后通过其ID查找用户,然后填充它:

//Index Route
    router.get("/", middleware.isLoggedIn, function(req, res){
        var user = req.user;
        User.findById(req.user._id, function(err, foundUser) {
            let user = foundUser;
            user.populate("groups").exec(function(err, allGroups){ 
               if(err){
                   console.log(err);
               } else {
                   res.render("groups/show", {groups: allGroups});
                   console.log(allGroups);
               }
           });
        });
    });

让我知道它是否有效!