TypeError :(中间值).populate不是函数

时间:2017-09-01 11:20:35

标签: node.js mongodb mongoose mongoose-schema mongoose-populate

我正在尝试获取单个用户的详细信息,包括他通过网站所做的所有评论(来自评论模式),但是每当我运行查询时,我都会获得 TypeError :(中间值) ).populate不是函数。我在互联网上以及在stackoverflow上搜索了相同的错误消息,但没有运气

显示路线

// profile page search
app.get("/:username", function(req, res) {

    User.findOne({ username: username }.populate("comments").exec(function(err, user) {
        if (err) {
            console.log(err);
            res.redirect("error");
        } else {
            if (user === null)
                res.render("invalid");
            else
                res.render("profile", { user: user });
        }
    }));

});

userSchema

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

    var UserSchema = new mongoose.Schema({
        id: String,
        fullname: String,
        username: String,
        comments: [
            {
                type: mongoose.Schema.Types.ObjectId,
                ref: "Comment"

            }
        ]
    });


UserSchema.plugin(passportLocalMongoose);

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

评论架构

var mongoose = require("mongoose");

var commentSchema= mongoose.Schema({
    text: String,
    author: {
        id: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User"
        },
        username: String
    }
});

module.exports = mongoose.model("comments", commentSchema);

我完全迷失在这里,请帮忙 提前致谢

2 个答案:

答案 0 :(得分:1)

您的右括号)的位置是错误的。只需在populate之前移动括号,它就应该有效。像这样:

// profile page search
app.get("/:username", function(req, res) {

  User.findOne({ username: username }).populate("comments").exec(function(err, user) {
    if (err) {
        console.log(err);
        res.redirect("error");
    } else {
        if (user === null)
            res.render("invalid");
        else
            res.render("profile", { user: user });
    }
  });
});

答案 1 :(得分:1)

// profile page search
app.get("/:username", function(req, res) {

        User.findOne({ username: username })
            .populate("comments")
.exec(function(err, user) {
            if (err) {
                console.log(err);
                res.redirect("error");
            } else {
                if (user === null)
                    res.render("invalid");
                else
                    res.render("profile", { user: user });
            }
        });

    });