【问题标题】:Mongoose "find" returns an empty arrayMongoose“查找”返回一个空数组
【发布时间】:2017-11-13 01:42:12
【问题描述】:

我正在尝试查找用户使用他的 userId 创建的所有博客。 我的博客有以下猫鼬模型

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

然后在我的 server.js 中我有这个

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


 })

但它返回一个空数组,我应该如何处理这个?

【问题讨论】:

  • 您的 findBlogs 获取用户 ID,然后将其视为博客 ID。当然,你没有得到任何匹配。应该是Blog.find({_creator: id}),或者类似的东西。
  • 那么我需要做什么才能将用户 ID 视为创作者 ID?

标签: javascript node.js mongodb mongoose postman


【解决方案1】:

线

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

应该说

return Blog.find({ _creator: id }).then((blogs) => {

【讨论】:

  • @maxpaj:是的,你没有:)
  • @maxpaj:不用担心 :) JFYI,如果您回复其他用户,您应该@mention他们,以便他们收到您的回复的通知
  • @SergioTulentsev 明白了 :)
【解决方案2】:

试试这个

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-04-27
    • 2021-09-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-12
    • 2012-12-20
    相关资源
    最近更新 更多