我正在尝试从不同的集合中查询用户名,然后才能插入另一个集合
这是 Post.js 文件
var mongoose = require('mongoose');
var user = require('./Users.js');
var PostSchema = mongoose.Schema({
uid : String,
text: String,
usename: String,
date: Date,
upvotes: Number,
downvotes: Number
});
var Post = module.exports = mongoose.model('Post', PostSchema);
module.exports.newPost = function(data){
var userid = data.uid;
var username = '';
user.User.findOne({_id:userid}, function(err,data){
if(err) req.flash('error_msg','Invalid username');
console.log(data)
});
};
这是路线Index.js 文件
var express = require('express');
var router = express.Router();
var Posts = require('../models/Post.js');
var uid = '';
router.get('/', ensureAuthenticated, function (req, res) {
uid = req.query.uid;
console.log(uid);
res.render('index')
})
router.post('/', function(req, res){
var post = req.body.post;
var date = Date();
var postData = {
uid : uid,
text: post,
usename: uid,
date: date,
upvotes: 0,
downvotes: 0
};
console.log(postData);
Posts.newPost(postData);
});
function ensureAuthenticated(req, res, next){
if(req.isAuthenticated()){
return next();
} else {
req.flash('error_msg','You are not logged in');
res.redirect('/users/login');
}
}
module.exports = router;
这是 User.js 文件
var mongoose = require('mongoose');
var bcrypt = require('bcryptjs');
// User Schema
var UserSchema = mongoose.Schema({
username: {
type: String,
index:true
},
password: {
type: String
},
email: {
type: String
},
name: {
type: String
}
});
var User = module.exports = mongoose.model('User', UserSchema);
当我运行服务器并提交以获取用户名时,我收到以下错误
TypeError: Cannot read property 'newPost' of undefined
at /home/a0_/Projects/Node/forum/routes/index.js:26:12
答案 0 :(得分:0)
在Mongoose实例中,方法应附加到架构:
PostSchema.methods.newPost = function(...) {...}