如何在node.js项目中保存mongodb中的记录? [英] How do I save a record in mongodb in a node.js project?
问题描述
我是MEAN堆栈的新手。有人可以帮我理解这个:
我创建一个新任务并保存它,但在索引页面我只能看到。
_id :5834ba711401ea28643cdfb8,__ v:0
没有其他属性。然而,task / index.jade中的 docs.length
随着每个添加的任务而增长。
我做错了什么?
非常感谢你!
tasks.js
I am new to the MEAN stack. Could someone please help me understand this:
I create a new task and save it, but in the index page I can only see.
_id: 5834ba711401ea28643cdfb8, __v: 0
No other attributes. However docs.length
in tasks/index.jade grows with every added task.
What am I doing wrong?
Thank you very much!
tasks.js
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/todo_development');
var Schema = mongoose.Schema;
var ObjectId = Schema.ObjectId;
// #9
var Task = new Schema({
task: String // #11
});
var Task = mongoose.model('Task', Task); // #10
router.get('/', function(req, res) {
Task.find({}, function (err, docs){
res.render('tasks/index', {
title: ' Ornbo | Todos index view' ,
docs: docs // #12
});
});
});
// @4
router.get('/new', function(req,res){
res.render('tasks/new.jade', {
title: 'New Task'
});
});
//#5
router.post('/', function(req, res){
var task = new Task(req.body.item); // #6
task.save(function(err){ // #7
if(!err){
res.redirect('/tasks'); // #8
} else {
res.redirect('/tasks/new');
}
});
});
module.exports = router;
tasks / index.jade
tasks/index.jade
- if(docs.length)
span number of records: #{docs.length}
table
tr
th Task
each task in docs
tr
td Do: [#{task}]
我尝试过:
我尝试重命名属性并查看MongoVUE中的数据库。
What I have tried:
I have tried renaming the attribute and looking at the DB in MongoVUE.
推荐答案
此代码修复了这种情况:
This code fixed the situation:
app.use(bodyParser.urlencoded({ extended: true }));
req.body.task
undefined
直到 extended
设置为 true
以支持URL编码的主体。
req.body.task
was undefined
until extended
was set to true
to support URL-encoded bodies.
这篇关于如何在node.js项目中保存mongodb中的记录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!