简体   繁体   中英

Post Form Data to Array of Existing MongoDB Document using Express and Mongoose

I'm attempting to create a Mongo document then update the document form a form to have additional properties, one of which has an array of objects.

I'm able to save everything except objects to the address array.

The following code snippets show my current attempt to save an object to the address array. I feel like I'm missing a push or shift which I've tried and can't seem to get syntax correct.

Mongoose Schema:

var UserSchema = new mongoose.Schema({
     username: { type: String, lowercase: true }
    , password: { type: String }
    , email: { type: String, lowercase: true }
    , phone: { type: String }
    , newsletter: Boolean
    , created: { type: Date, default:   Date.now }
    , address: [{
        nickname: { type: String }
        , streetAddress: { type: String }
        , streetAddress2: { type: String }
        , state: { type: String }
        , zip: { type: String }
    }]    
});

Model Methods: First I create an account. The form only asks for username, email, password then redirects to the jade file where users can fill out the rest of the form.

module.exports = exports = function(){
    //create account
    this.createAndSave = function (req, res ) {
        new User({
            username: req.body.username
            , password: req.body.password
            , email: req.body.email
            , phone: req.body.phone
            , address: [{
               nickname: req.body.nickname
               , streetAddress: req.body.streetAddress
               , streetAddress2: req.body.streetAddress2
               , state: req.body.state
               , zip: req.body.zip
            }]
        }).save(function (err, user){
            if (err) throw err;
            req.session.isLoggedIn = true;
            req.session.user = user.username;
            res.redirect('/account/' + user.username)
        })
    }

//update account
this.updateRequest = function (req, res) {
    User.update({username: req.user.username}, {
        username: req.body.username
        , email: req.body.email
        , phone: req.body.phone
        , newsletter: req.body.newsletter
        , address: [{
           nickname: req.body.nickname
           , streetAddress: req.body.streetAddress
           , streetAddress2: req.body.streetAddress2
           , state: req.body.state
           , zip: req.body.zip
        }]
      }, function (err) {
        res.redirect("/account/" + req.body.username);
    });
}

Jade Template: (I'm sure this could be cleaner)

h1 Edit User
#{user}
form(method="POST", action="/account/#{user.username}")
    input(type="hidden", name="_method", value="PUT")
    .form-group
        label(for="username") Name
        input#name.form-control(type="text", name="username", value= user.username )

    .form-group
        label(for="email") Email
        input#email.form-control(type="email", name="email", value= user.email )

    .form-group
        label Phone
        input#phone.form-control(type="text", name="phone", value= user.phone )

    .form-group
        label Newsletter Opt In/Out 
        input#newsletter(type="checkbox", name="newsletter", checked=(true===false ? "checked" : undefined))

    if(user.address.length > 0)
            for (var i = 0; i < user.shippingAddresses.length; i++) {}>)
                .form-group
                    label Street Address
                    input#address.form-control(type="text", name="streetAddress", value= user.shippingAddresses[i].streetAddress )

                .form-group
                    label Address Continued
                    input#address2.form-control(type="text", name="streetAddress2", value= user.shippingAddresses[i].streetAddress2 )

                .form-group
                    label Zip Code
                    input#zip.form-control(type="text", name="zip", value= user.shippingAddresses[i].zip )
    else
                .form-group
                    label Location Nick Name
                    input#address.form-control(type="text", name="nickname", value= )

                .form-group
                    label Street Address
                    input#address.form-control(type="text", name="streetAddress", value= )

                .form-group
                    label Address Cont.
                    input#address2.form-control(type="text", name="streetAddress2", value= )
                .form-group
                    label State
                    input#state.form-control(type="text", name="state", value= )
                .form-group
                    label Zip Code
                    input#zip.form-control(type="text", name="zip", value= )


    button(type="submit") Update Account

Additionally there is another address only form which is why the address is an array.

Any direction would be very helpful as I may go unhinged at any moment. If you any further code let me know.

Something else to note, I'm not able to get any of the updated data from the update function to save to mongo.

Thanks!

Here is the solution I came up with. I find the document to update and push an object to the property that stores the array.

Example method:

this.addAddress = function (req, res) {
    var newAddress = {
           nickname: req.body.nickname,
           streetAddress: req.body.streetAddress,
           streetAddress2: req.body.streetAddress2,
           state: req.body.state,
           zip: req.body.zip
    }
    User.update({username: req.session.user}, { $push : {
            address: newAddress
        }}, {upsert: true}, function ( err ) {
                if(err){
                        console.log(err);
                }else{
                        console.log("Successfully added");
                }
        })
}

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