2017-09-04 124 views
0

我想让这个贴子的创建者成为一个用户模式。所以,我有2个模式猫鼬填充不是一个功能

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

当用户创建一个新的岗位,我救他_id到一个新的职位对象

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

当我想恢复与他们分配的作者

所有职位
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 
    }); 

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

+0

当你创建你的新帖子时,你会打电话给post.save()吗? –

+0

@SteveHolgado是 –

+0

你的** Post.find()。populate('createdBy')。exec()**调用的结果是什么?你得到的文件,但** createdBy **字段没有填充? ...或者你没有得到退回的文件? –

回答

1

.exec()返回Promise并且没有方法.sort()

.sort().exec()之前去为Post.find(...).populate(...).sort(...).exec(...)

看在documentation第三个例子。