我正在尝试更新我的MongoDB数据库上的阵列,但这显示了这一点。 我试图按照官方文档中给出的每个步骤进行操作,但是它不起作用。请帮助
尝试了官方文档,没有用。
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const { ensureAuthenticated, forwardAuthenticated } = require('../config/auth');
// Welcome Page
router.get('/', forwardAuthenticated, (req, res) => res.render('welcome'));
//DB Config
const db = require('../config/keys').MongoURI;
// Dashboard
router.get('/dashboard', ensureAuthenticated, (req, res) => {
mongoose
.connect(db, {useNewUrlParser: true})
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
res.render('dashboard', {
user: req.user
})
});
router.post('/dashboard', ensureAuthenticated, (req, res) => {
req.flash('success_msg', 'Book added, Reload to view the changes');
res.redirect('dashboard')
});
// Add
router.post('/add', ensureAuthenticated, (req, res) => {
const { name } = req.body;
console.log(name);
const newBooks = req.user.books;
newBooks.push(name);
console.log(newBooks);
db.users.updateOne(
{"email" : req.user.email},
{$set: { "name" : "hello"}});
res.render('dashboard', {
user: req.user
});
});
module.exports = router;
答案 0 :(得分:2)
尝试一下!
const User = require('../models/users') //important (look for the user model)
const express = require('express');
const router = express.Router();
const mongoose = require('mongoose');
const { ensureAuthenticated, forwardAuthenticated } = require('../config/auth');
// OUTSIDE !!!!!!!!!!!!
mongoose
.connect(db, {useNewUrlParser: true})
.then(() => console.log('MongoDB Connected'))
.catch(err => console.log(err));
//DB Config
const db = require('../config/keys').MongoURI;
router.get('/dashboard', ensureAuthenticated, (req, res) => {
res.render('dashboard', {
user: req.user
})
});
outer.post('/dashboard', ensureAuthenticated, (req, res) => {
req.flash('success_msg', 'Book added, Reload to view the changes');
res.redirect('dashboard')
});
// Add
router.post('/add', ensureAuthenticated, (req, res) => {
const { name } = req.body;
console.log(name);
const newBooks = req.user.books;
newBooks.push(name);
console.log(newBooks);
var email = req.user.email;
User.findOneAndUpdate(
{"email" : email},
{$set: { "name" : "hello"}});
res.render('dashboard', {
user: req.user
});
});
module.exports = router;
答案 1 :(得分:0)
您正试图调用猫鼬模型方法,但实际上,您是在数据库URI字符串上调用它。
相反,您需要执行以下操作:
const User = mongoose.model('User');
User.updateOne({"email" : req.user.email},
{$set: { "name" : "hello"}});
以上假设您的用户架构已定义为“用户”。