您的位置:首页技术文章
文章详情页

javascript - express router.get()函数与mongoose连用错误

【字号: 日期:2023-09-20 11:38:06浏览:15作者:猪猪

问题描述

下列代码中被注释部分存在错误,如果将两端注释符号/**/去掉就会出现render渲染错误。

var express = require(’express’);const mongoose = require(’mongoose’);const UserModel=mongoose.model(’UserModel’);var router = express.Router();const ObjectId = mongoose.Schema.Types.ObjectId;const connection = mongoose.connect(’mongodb://localhost/likeread’).connection;connection.on(’error’,(err)=>{console.log(err); }) .on(’open’,(res)=>{console.log(’success!’); });/* GET users listing. */router.get(’/’, function(req, res, next) { /*var user_model = new UserModel({username:’xiao’,email:’email@.com’}); user_model.save((err,res)=>{if(err) console.log(err); }); connection.disconnect((err,res)=>{if(err) console.log(err); });*/ res.render(’user.pug’);});module.exports = router;错误

at EventEmitter.render (D:nodelikereadnode_modulesexpresslibapplication.js:580:17) at ServerResponse.render (D:nodelikereadnode_modulesexpresslibresponse.js:966:7) at D:nodelikereadapp.js:60:7 at Layer.handle_error (D:nodelikereadnode_modulesexpresslibrouterlayer.js:71:5) at trim_prefix (D:nodelikereadnode_modulesexpresslibrouterindex.js:315:13) at D:nodelikereadnode_modulesexpresslibrouterindex.js:284:7 at Function.process_params (D:nodelikereadnode_modulesexpresslibrouterindex.js:335:12) at next (D:nodelikereadnode_modulesexpresslibrouterindex.js:275:10) at Layer.handle_error (D:nodelikereadnode_modulesexpresslibrouterlayer.js:67:12) at trim_prefix (D:nodelikereadnode_modulesexpresslibrouterindex.js:315:13) at D:nodelikereadnode_modulesexpresslibrouterindex.js:284:7 at Function.process_params (D:nodelikereadnode_modulesexpresslibrouterindex.js:335:12) at Immediate.next (D:nodelikereadnode_modulesexpresslibrouterindex.js:275:10) at Immediate.<anonymous> (D:nodelikereadnode_modulesexpresslibrouterindex.js:635:15) at runCallback (timers.js:668:20) at tryOnImmediate (timers.js:639:5)

问题解答

回答1:

connection.disconnect((err,res)=>{ if(err)console.log(err);});*/ res.render(’user.pug’);

你这是什么鬼? res.render(’user.pug’);放到函数外面?

回答2:

render和disconnect应该放到save完成的回调函数内部执行

标签: JavaScript
相关文章: