简体   繁体   中英

Updating array in mongodb document within Mean.js

I'm just beginning with mean.js and getting my feet wet building out a custom article module with a few basic extra properties. I'm trying to add a list of tags that are added on the create form via an text input field. As you can see below, this works fine when they're freshly created. I can see the tags array in the newly created document in the terminal. When I load the edit view the tags field is populated with the elements of the tags array separated by commas. That seems ok. Now I want to simply add new tags after the current ones, separating each new tag with a comma, and have the array updated with the new list. However, after performing the update the tags array elements change to one long string containing all tags. I had a look at the server side update function but I'm not quite sure what to do there to make it work. It appears the article is being updated as a complete object so maybe I need to extract the tags array and perform a push new tags separately?Anyone know what I'm doing wrong?I've been troubleshooting it for a day or so now and am out of ideas.Thanks in advance!

JSON print of new article:

{
"user" : ObjectId("545db575197ad8a949894a18"),
"desc" : “some description”,
"_id" : ObjectId("546115f20a3048862033d393"),
"created" : ISODate("2014-11-10T19:45:54.079Z"),
"tags" : [
    "here”,
    "be",
    "tags"
],
"name" : "Test”,
"__v" : 0
}

JSON print after update - Note: tags are now one string

{
"__v" : 1,
"_id" : ObjectId("546115f20a3048862033d393"),
"created" : ISODate("2014-11-10T19:45:54.079Z"),
"desc" : "some description",
"name" : "Test",
"tags" : [
    "here,be,tags,more"
],
"user" : ObjectId("545db575197ad8a949894a18")
}

// Create new article

    $scope.create = function() {
        console.log('Tags before split: ' + this.tags);
        var tags = this.tags;
        var tags = tags.split(" ");
        console.log(“Tags array “ + tags);

        // Create new article object
        var article = new Article ({
            name: this.name,
            desc: this.desc,
            tags: tags

        });

// Update existing article

        $scope.update = function() {

        var article = $scope.article;
        console.log(“This " 
            + article);

        article.$update(function() {
            $location.path('articles/' + article._id);
        }, function(errorResponse) {
            $scope.error = errorResponse.data.message;
        });
    };

Tags input field in create-article view

        <div class="form-group">
                <label class="control-label" for="tags">Tags</label>
                <div class="controls">
                    <input type="text" data-ng-model="tags" id="tags" class="form-control" placeholder="Tags" required>
                </div>
        </div>

Tags input field in update-article view

           <div class="form-group">
                <label class="control-label" for="tags">Tags</label>
                <div class="controls">
                    <input type="text" data-ng-model="article.tags" id="tags" class="form-control" placeholder="Tags" required>
                </div>
            </div>

Update article server side controller

 /**
 * Module dependencies.
 */
 var mongoose = require('mongoose'),
 errorHandler = require('./errors.server.controller'),
 Article = mongoose.model('Article'),
 _ = require('lodash');

exports.update = function(req, res) {   

var article = req.article;

article = _.extend(article , req.body);

article.save(function(err) {
    if (err) {
        return res.status(400).send({
            message: errorHandler.getErrorMessage(err)
        });
    } else {
        res.jsonp(article);
    }
});
};

The articles model

var ArticleSchema = new Schema({
name: {
    type: String,
    default: '',
    required: 'Please fill Article name',
    trim: true
},
desc: String,
tags: [String],
created: {
    type: Date,
    default: Date.now
},
user: {
    type: Schema.ObjectId,
    ref: 'User'
}
});

mongoose.model('Article', ArticleSchema);

您需要先拆分标签,然后再进行更新,就像在create函数中一样。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM