// model starts here - Post schema//
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var postSchema = new Schema({
imagePost: { images: [{ url: String, text: String }] } });
module.exports = mongoose.model('Post',postSchema);
// model ends here //
// route (controller) start here- RESFUL API CRUD OPERTIONS //
var Post = require ('../models/ques');
var User = require ('../models/user');
var config = require ('../../config');
module.exports = function(app, express) {
var api = express.Router();
//POST method is for creating the posts in the database,
api.post('/createpost', function(req, res){
var new_post = new Post();
new_post.imagePost = { images: [] };
for (var i in req.body.post_content.images) {
var image = req.body.post_content.images[i];
var imageObj = { url: image['url'], text: image['text'] };
new_post.imagePost.images.push(imageObj);
}
new_post.save(function(err){ // if there is an error
if(err){
res.send(err);
return;
}
res.json({message:'Post has been created'})
});
});
//GET method is for fetching all the posts from the database,
api.get('/postdb',function(req, res){
Post.find({}, function(err, postdb){
if(err){
res.send(err);
return;
}
res.json(postdb);
});
});
// route ends here//
我正在学习平均堆栈,基本上我处于初学者阶段,我已经观看了几个视频讲座,并学习了如何在mongodb中存储数据但是没有一个讲座我找到了如何存储多个字段的数组,如上例所示,不知怎的,我在stackoverflow link上得到了一个例子,但是我无法保存url和text的值,而且它总是崩溃。有错误
TypeError: Cannot read property 'images' of undefined
at C:\projects\rt\app\routes\api.js:17:36
at Layer.handle [as handle_request] (C:\projects\rt\node_modules\express\lib\router\layer.js:95:5)
at next (C:\projects\rt\node_modules\express\lib\router\route.js:131:13)
at Route.dispatch (C:\projects\rt\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (C:\projects\rt\node_modules\express\lib\router\layer.js:95:5)
at C:\projects\rt\node_modules\express\lib\router\index.js:277:22
at Function.process_params (C:\projects\rt\node_modules\express\lib\router\index.js:330:12)
at next (C:\projects\rt\node_modules\express\lib\router\index.js:271:10)
at Function.handle (C:\projects\rt\node_modules\express\lib\router\index.js:176:3)
at router (C:\projects\rt\node_modules\express\lib\router\index.js:46:12)
at Layer.handle [as handle_request] (C:\projects\rt\node_modules\express\lib\router\layer.js:95:5)
at trim_prefix (C:\projects\rt\node_modules\express\lib\router\index.js:312:13)
at C:\projects\rt\node_modules\express\lib\router\index.js:280:7
at Function.process_params (C:\projects\rt\node_modules\express\lib\router\index.js:330:12)
at next (C:\projects\rt\node_modules\express\lib\router\index.js:271:10)
at logger (C:\projects\rt\node_modules\morgan\index.js:144:5)