0

i'm trying to find all blogs that a user has created with his userId. I have the following mongoose model for the blog

 var mongoose = require('mongoose');


 var BlogSchema = new mongoose.Schema({
     title:{
    type: String,
    required: true,
},
content:{
    type: String,
    required: true
},
_creator:{
    type: mongoose.Schema.Types.ObjectId,
    required: true
     }
 })

 BlogSchema.statics.findBlogs = function(id){
var Blog = this;

return Blog.find(id).then((blog)=>{
    console.log(blog)
}).catch((e)=>{
    console.log('failed')
})



 }

 var Blog = mongoose.model('Blogs', BlogSchema)

 module.exports = {Blog};

then in my server.js i have this

 app.get('/get/blogs', authenticate, (req, res)=>{
  var userId = req.user._id
   console.log(userId)
   Blog.findBlogs(userId).then((data)=>{
    res.send(data)

    }).catch((e)=>{
    res.sendStatus(404)
  })


 })

but it returns an empty array, how should i approach this?

2
  • Your findBlogs takes a user id and then treats it as a blog id. Of course, you don't get any matches. Should be Blog.find({_creator: id}), or something like that. Commented Jun 11, 2017 at 14:25
  • so what do i need to do so that it treats the user id, as the creators id? Commented Jun 11, 2017 at 14:27

2 Answers 2

1

The line

return Blog.find(id).then((blog) => {

should probably say

return Blog.find({ _creator: id }).then((blogs) => {
Sign up to request clarification or add additional context in comments.

3 Comments

@maxpaj: yes, that you didn't :)
@maxpaj: no worries :) JFYI, if you respond to other users, you should @mention them, so that they get notified of your replies
@SergioTulentsev got it :)
0

Try this

blog.find({creatorid:user.id},function(err,data){
//data will be here
})

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.