Mongoose populate 不是一个函数

Azo*_*son 1 mongoose mongodb mongoose-populate

我希望帖子的创建者是用户架构。所以我有2个模式

后.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);
Run Code Online (Sandbox Code Playgroud)

用户.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);
Run Code Online (Sandbox Code Playgroud)

当用户创建新帖子时,我将他的 _id 保存到新的帖子对象中

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

当我想恢复指定作者的所有帖子时

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
    });
Run Code Online (Sandbox Code Playgroud)

尽管我遵循了文档,但它不起作用。我得到的错误是TypeError: Post.find(...).populate(...).exec(...).sort is not a function 我做错了什么?我错过了什么吗?也许两个模型不在同一个文件中?

小智 7

删除 execPopulate() 它可能会起作用。这对我有用。