2017-09-04 8 views
0

投稿の作成者をユーザーのスキーマにします。だから私は、ユーザーが新しい投稿を作成すると、私は新しいポストオブジェクトモンゴーズの母集団は関数ではありません

const post= new Post({ 
     body: req.body.body, 
     createdBy:user._id, 
     createdAt:Date.now() 
}); 
に彼の_idを救う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); 

を持っています

そして、私は割り当てられた著者とすべての投稿を回復したいとき

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 yes –

+0

** Post.find()。populate( 'createdBy')。exec()**コールの結果は何ですか?ドキュメントを取得しますか?** createdBy **フィールドには値が設定されていませんか? ...または返された書類がありませんか? –

答えて

1

.exec()はPromiseを返し、.sort()というメソッドはありません。 Post.find(...).populate(...).sort(...).exec(...)

のように.exec()documentationに第三の例を見て前に

.sort()は行きます。

関連する問題