我希望帖子的创建者成为用户架构。所以我有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);
当用户创建新帖子时,我将他的_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 :(得分:1)
.exec()返回一个Promise,没有名为.sort()
的方法。
.sort()
与.exec()
Post.find(...).populate(...).sort(...).exec(...)
相同
查看documentation中的第3个示例。