0

I am using the CRUD module in mean.js to add data to my webapp.

I am having no issues adding in strings etc, however I am having issues with embeded data.

My desired data format is below.

{
    "_id":"5559abc02ef1bcdc2e6e6137",
    "messages": [
        "title":"title of msg",
        "msg":"msg content"
    ],
    "created":"2015-05-19T09:30:25.117Z",
    "department":"finance",
    "name":"accounts receivable"
}

From this snippet I want to be able to push data into the messages field. I have seen ideas on how to do this in posts such as this pushing object into array schema in Mongoose.

However I am not sure how I can implement this soloution with angular. So far I have the below, which works for all fields except the messages field.

    var mongoose = require('mongoose'),
        Schema = mongoose.Schema;

    /**
     * Team Schema
     */
    var TeamSchema = new Schema({
        name: {
            type: String, //eg accounts receivable
            default: '',
            required: 'Please fill Team name',
            trim: true
        },
        department: {
            type: String, //eg finance
            default: '',
            required: 'Please fill department',
            trim: true
        },
        messages: [
          {
            title: {type: String},
            msg: {type: String}
          }
        ],

        created: {
            type: Date,
            default: Date.now
        },
        user: {
            type: Schema.ObjectId,
            ref: 'User'
        }
    });

    /**
     * Create a Team
     */

    var mongoose = require('mongoose'),
        errorHandler = require('./errors.server.controller'),
        Team = mongoose.model('Team'),
        _ = require('lodash');

    exports.create = function(req, res) {
        var team = new Team(req.body);
        team.user = req.user;
        team.save(function(err) {
            if (err) {
                return res.status(400).send({
                    message: errorHandler.getErrorMessage(err)
                });
            } else {
                res.jsonp(team);
            }
        });
    };

    /**
     * Angular controller
     */

    $scope.create = function() {
        // Create new Team object
        var team = new Teams ({
            name: this.name,
            department: this.department,
            messages: this.messages.title
            //this.messages[0].title
        });

        // Redirect after save
        team.$save(function(response) {
            $location.path('teams/' + response._id);

            // Clear form fields
            $scope.name = '';
            $scope.department = '';
            $scope.messages.title = '';
        }, function(errorResponse) {
            $scope.error = errorResponse.data.message;
        });
    };

Angular View

    <form class="form-horizontal" data-ng-submit="create()" novalidate>
        <fieldset>
            <div class="form-group">
                <label class="control-label" for="name">Name</label>
                <div class="controls">
                    <input type="text" data-ng-model="name" id="name" class="form-control" placeholder="Name" required>
                </div>
            </div>
            <div class="form-group">
                <label class="control-label" for="department">Department</label>
                <div class="controls">
                    <input type="text" data-ng-model="department" id="department" class="form-control" placeholder="Department" required>
                </div>
            </div>
            <div class="form-group">
                <label class="control-label" for="messages">messages</label>
                <div class="controls">
                    <input type="text" data-ng-model="messages.title" id="messages" class="form-control" placeholder="messages">
                </div>
            </div>                
            <div class="form-group">
                <input type="submit" class="btn btn-default">
            </div>
            <div data-ng-show="error" class="text-danger">
                <strong data-ng-bind="error"></strong>
            </div>
        </fieldset>
    </form>

How can I save the messages title and msg like I am saving the other items?

I would also potentially want to give users the ability to add their own fields to this messages field so they could add their own customization to the model, so it would be good if the solution rather than explicitly mentioned title and message, instead referenced each item.

1 Answer 1

1

You need to create an array of messages in the $scope.create function, something like this when creating the new team object:

// Create new Team object
var team = new Teams ({
    name: this.name,
    department: this.department,
    messages: [
        { title: this.messages.title, msg: "" }
    ]
});

In order to add multiple messages with different titles etc, I'd create a scope variable to hold the messages (e.g. $scope.messages = [{title:"",msg:""}]) then use ng-repeat to iterate over it in your template to create multiple inputs:

<input type="text" data-ng-repeat="message in messages" data-ng-model="message.title" id="messages" class="form-control" placeholder="messages">

You could then have a button for "add message", wire up it's click to push another {title:"",msg:""} onto the $scope.messages array. Lastly, you'd then update your $scope.create function again to add that array as the value for the messages field:

// Create new Team object
var team = new Teams ({
    name: this.name,
    department: this.department,
    messages: this.messages
});

On clearing the form, just set $scope.messages back to its initial single-item array value.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the answer I am a little confused though about what to put in the new Team object part? I have tried both your suggestions messages: [{ title: this.messages.title, msg: "" }] and messages: this.messages both seem to return me messages: "object Object" at this stage? Do you know where I might be going wrong here?
@ak85 Do you have the definition of the Teams class available?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.