Search code examples
mongodbmongoosemongoose-populate

Mongoose populate is not a function


I want the post's creator to be a user Schema. So i have 2 Schema

post.js

const mongoose=require('mongoose');
mongoose.Promise = global.Promise;
const Schema= mongoose.Schema;

const postSchema= new Schema({
    body:{ type: String, required:true, validate:bodyValidators},
    createdBy: { type: Schema.Types.ObjectId,ref:'User'}, // this one
    to: {type:String, default:null },
    createdAt: { type:Date, default:Date.now()},
    likes: { type:Number,default:0},
    likedBy: { type:Array},
    dislikes: { type:Number, default:0},
    dislikedBy: { type:Array},
    comments: [
        {
            comment: { type: String, validate: commentValidators},
            commentator: { type: String}
        }
    ]
});



module.exports = mongoose.model('Post',postSchema);

user.js

const mongoose=require('mongoose');
mongoose.Promise = global.Promise;
const Schema= mongoose.Schema;

const userSchema=new Schema({
    email: { type: String, required: true, unique: true, lowercase: true, validate: emailValidators},
    username: { type: String, required: true, unique: true, lowercase: true, validate: usernameValidators},
    password: { type: String, required: true,validate: passwordValidators},
    bio: { type:String,default:null},
    location: {type:String, default:null},
    gender: {type:String,default:null},
    birthday: { type:Date,default:null},
    img: { type:String, default:'Bloggy/uploads/profile/avatar.jpeg'}
});

module.exports = mongoose.model('User',userSchema);

When a user creates a new post, I save his _id into a new post object

const post= new Post({
        body: req.body.body,
        createdBy:user._id,
        createdAt:Date.now()
});

And when i want to recover all posts with their assigned author

router.get('/allPosts',(req,res)=>{
        Post.find().populate('createdBy').exec((err,posts)=>{
            if(err){
                res.json({success:false,message:err});
            }
            else{
                if (!posts) {
                    res.json({success:false,message:"No posts found"});
                }
                else{
                    res.json({success:true,posts:posts});
                }
            }
        }).sort({'_id':-1}); // the latest comes first
    });

It doesn't work though i've followed the documentation. The error i get is TypeError: Post.find(...).populate(...).exec(...).sort is not a function What am I doing wrong ? Am I missing something ? Maybe the fact that both models are not in the same file ?


Solution

  • .exec() returns a Promise and has no method called .sort().

    .sort() goes before .exec() as in Post.find(...).populate(...).sort(...).exec(...)

    Look at 3rd example in the documentation.