如何创建新文档更新现有文档 [英] How to create a new document & update an existing document

查看:129
本文介绍了如何创建新文档更新现有文档的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个民意测验应用程序,用户可以在其中投票给定民意测验中的选项.每个民意调查都有2个或更多选项作为子文档.每个选项的投票都属于另一个集合中的文档(用于身份验证和唯一投票).

I'm developing a polls application, in which a user can vote for an option in a given poll. each poll has 2 or more options as subdocument. each of these options have votes that are documents in another collection (for authentication and unique voting purposes).

我可以使用民意调查CRUD(可以毫无问题地创建,读取,更新和删除),但是当我尝试创建投票功能(即更新民意调查文档poll_option子文档+创建新的投票文档)时,我的问题就开始了

I have the polls CRUD working (I can create, read, update and delete without a problem), but my problem begins when im trying to create a vote function, i.e update a poll documents poll_option subdocument + creating a new vote document.

poll.server.model.js

poll.server.model.js

'use strict';

/**
 * Module dependencies.
 */
var mongoose = require('mongoose'),
    Schema = mongoose.Schema;

/**
 * Poll Schema
 */
var PollSchema = new Schema({
    poll_id: {type:Number},
    user: {
        type: Schema.ObjectId,
        ref: 'User'
    },
    poll_question: {type:String},
    poll_language: [{
        type:Schema.ObjectId,
        ref: 'Language'
    }],
    poll_category: [{
        type: Schema.ObjectId,
        ref: 'Category'
    }],
    poll_description: {type:String},
    poll_description_raw: {type:String},
    poll_weight_additional: {type:Number},
    poll_flag_active:{type:Number,default:1},
    poll_flag_18plus:{type:Number,default:0},
    poll_flag_expire:{type:Number,default:0},
    poll_flag_deleted:{type:Number,default:0},
    poll_flag_moderated:{type:Number,default:0},
    poll_flag_favourised:{type:Number,default:0},
    poll_date_expiration:{type:Date},
    poll_date_inserted:{type:Date,default:Date.now},
    poll_flag_updated:{type:Date},
    show_thumbs:{type:Boolean},
    comments: [{
        type: Schema.ObjectId,
        ref: 'Comment'
    }],
    poll_options: [{
        option_text:{type:String},
        option_thumb:{type:Number,default:0},
        votes:[{
            type: Schema.ObjectId,
            ref: 'Vote'
        }]
    }]
});

mongoose.model('Poll', PollSchema);

但是从头开始,这是前端控制器中的表决功能

but ill start from the front, this is the vote function in the frontside controller

// Vote
            $scope.vote = function(){

                $scope.votes = Votes.query();

                var vote = new Votes({
                    _id:pollId,
                    option_id:optionId
                });

                vote.$save(function(response){
                    // ... //
                }, function(errorResponse) {
                    $scope.error = errorResponse.data.message;
                });
            };

这是投票工厂:

angular.module('polls').factory('Votes', [ '$resource', 
    function($resource) {
        return $resource('polls/:pollId/votes/:optionId', {
            pollId: '@_id',
            optionId: '@option_id'
        }, {
            update: {
                method: 'PUT'
            }
        });
    }
]);

到目前为止,一切都运行良好,即当我运行$ scope.vote();时.功能,我在浏览器控制台中得到以下响应:

up to this point everything runs well, i.e when i run the $scope.vote(); function i get this response in the browser console:

POST http://localhost:3000/polls/548c6da001ec1f4ba2860c38/votes/548c6da001ec1f4ba2860c3a 404 (Not Found)

据此我收集到对该URL的调用,控制器+服务(角度)正常工作.

from this i gather that the call to that url is made, controller + service (angular) working.

按照meanjs文章示例,我了解我需要将optionId参数映射到实际选项

following the meanjs article example, i understand that i need to map the optionId param to an actual option

poll.server.route.js

poll.server.route.js

'use strict';

/**
 * Module dependencies.
 */
var users = require('../../app/controllers/users.server.controller'),
    polls = require('../../app/controllers/polls.server.controller');

module.exports = function(app) {
    // Poll Routes
    app.route('/polls')
        .get(polls.list)
        .post(polls.create);

    app.route('/polls/:pollId')
        .get(polls.read)
        .put(polls.update)
        .delete(polls.delete);

    app.route('/polls/:pollId/votes/:optionId')
        .put(polls.vote);

    app.param('pollId', polls.pollByID);
    app.param('optionId', polls.pollOptionByID);

};

但是无论我做什么,我都会继续获取404!这是polls.server.controller.js中的polls.pollOptionByID函数

but no matter what i do, i keep on getting the 404! here is the polls.pollOptionByID function in the polls.server.controller.js

exports.pollOptionByID = function(req, res, next, id) {
    Poll.findOne({'poll_options._id':id}).exec(function(err,poll_option){
        console.log('hi');
        if (err) return next(err);
        if (!poll) return next(new Error('Failed to load poll option ' + id));
        req.poll_option = poll_option;
        next();
    });
}

但是我什至没有到达那儿.我在控制台日志中看不到那个嗨.是的,当然,我尝试了没有console.log的情况,但是没有任何效果,我一直只收到404.我在做什么错?如何实现我的目标,即创建一个新的投票文档+将其映射到给定投票文档中的poll_option子文档?

but I don't even get there. I don't see that hi in the console log. and yes, of course I tried without the console.log but nothing works, I keep getting only 404. What am I doing wrong? How can I achieve my goals i.e creating a new vote document + mapping it to a poll_option subdocument in a given poll document?

推荐答案

如此,还有惠灵顿·赵( https://www.facebook.com/AlphanumericSoup?fref=ufi )在meanjs fb小组(

so, as wellington zhao (https://www.facebook.com/AlphanumericSoup?fref=ufi) at the meanjs fb group (https://www.facebook.com/groups/meanjs/463004417186215/?comment_id=463027443850579&notif_t=group_comment) pointed out:

您似乎要尝试发布到路线 (/polls/:pollId/votes/:optionsId)仅定义了PUT.更改 到另一个,然后查看404是否仍然存在.

It looks like you're trying to POST to a route (/polls/:pollId/votes/:optionsId) that only has PUT defined. Change it to one or the other and see if 404 persists.

所以我将路线定义更改为post和viola,它起作用了!希望我能帮助其他菜鸟避免数小时的诅咒和大喊大叫的原因.

so i changed the route definition to post and viola, it worked! hoped i help other noobs to avoid hours of cursing and shouting why.

这篇关于如何创建新文档更新现有文档的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆