简体   繁体   中英

TypeError: (intermediate value).populate is not a function

I am trying to get the details of the single user including all of his comments(from comment schema) that he made through the website but on show route whenever i run the query i get the TypeError: (intermediate value).populate is not a function . I have searched alot on internet as well as on stackoverflow on the same error message but no luck

Show route

// 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);

Comments schema

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

I am totally lost here, please help Thanks in advance

Your placement of closing parenthesis ) is wrong. Just move the parenthesis before populate , and it should work. Like this:

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

    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM