【发布时间】: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