Express+Mongoose建站常见报错原因及方法总结

mongoose populate

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Line.find({issues:id}, function (err, lines) {
Issue
//在line集合中查找issues字段id和issue集合的id相同的line
//使用findOne,只取最后插入的一条
.findOne({_id:id})
//等价于populate({path:'belongLineId',select:'name'})
.populate('belongLineId','name')
.exec(function(err,issue){
console.log('lines:')
console.log(lines);
console.log('issue:');
console.log(issue);
res.render('issueDetail', {
title: issue.title,
lines: lines,
issue: issue
})
})
})
  • populate中的path的值必须为issue集合里的字段,比如这里belongLineId是issue里的字段
  • populate中的select的值必须为line集合里的字段,比如这里nameline集合的字段

显示CastError: Cast to ObjectId failed for value ,length为0

通常是在schema中忘记添加相应地字段,或者在controller里render时忘记传递字段值

出现can’t set header after they are sent

通常是controller里render了两次,或者redirect了两次

find()与findOne()的区别

1
var id = req.params.id
  • find(id)是遍历出所有的数组
  • findOne({_id:id})是查找出一个这个id浏览器当前页面参数相同的值

打印出当前用户

  • req.session.user._id
  • req.session.user.name

转换日期

  • npm install moment --save
  • #{moment(issue.start).format('YYYY/MM/DD')}