2015-06-06 4 views
3

У меня есть проблема с извлечением данных.Извлечение данных Nodejs и Mongoose

У меня есть схема мангуста.

PostSchema.methods.getAuthor = function() { 
    this.model('User').findById(this.author).exec(function (err, author){ 
     if (author) { 
      console.log(author.username); 
      return author.username; 
     }; 
    }); 
}; 

mongoose.model('Post', PostSchema); 

и getMethod

exports.getPost = function (req, res) { 
    return Post.findById(req.params.id, function (err, post) { 
     if (!post) { 
      res.statusCode = 404; 
      return res.send({ error: 'Not found' }); 
     } 
     if (!err) { 
      var author = post.getAuthor(); 
      console.log('author is: ', author); 

      return res.send({ status: 'OK', post:post }); 
     } else { 
      res.statusCode = 500; 
      return res.send({ error: 'Server error' }); 
     } 
    }); 
}; 

Когда я называю post.getAuthor() внутри getPost метод он нашел работу и Пользователя по Id. Но var author = post.getAuthor(); имеют undefined значение.

+1

Конечно, вы получите 'undefined', как вы пытаетесь присвоить значение асинхронной' функции getAuthor' синхронно. – zaynetro

ответ

3

Как отметил @zaynetro, вы неправильно вызываете свой getAuthor. Это асинхронный метод, поэтому вы должны принять параметр обратного вызова, или вы можете вернуть обещание.

Но то, что вы пытаетесь сделать, уже встроено в мангуст, его называемую населением запросов.

http://mongoosejs.com/docs/populate.html

Вы можете настроить эталонное свойство Post.author, что вы можете иметь мангуст решительность в документ для вас.

var postSchema = Schema({ 
    author: { 
     type: Schema.Types.ObjectId, 
     ref: 'User' 
    } 
}); 
mongoose.model('Post', postSchema); 

var userSchma = Schema({ 
    name: String 
}); 
mongoose.model('User', userSchema); 

Затем в вашем маршруте Ваш запрос будет выглядеть следующим образом:

Post 
    .findById(req.params.id) 
    .populate('author') 
    .exec(function(err, post) { 
     if (err) { 
      return res.status(500).send({ 
       error: 'Server error' 
      }); 
     } 
     // post.author contains the content of your author document 
     return res.send(post); 
    }); 
Смежные вопросы