简体   繁体   中英

Mongoose not saving data to mongodb?

I'm building a shopping cart using JavaScript, MongoDB & Node.js. I've been able to save all the site's products, users & sessions so far. After I complete my checkout form, my inputs should be saved to MongoDB. I should be able to see "orders" among the db collections. But when I type show collections into the command line, only products, users, sessions are shown.

This is the error message:

ValidationError: Order validation failed
    at MongooseError.ValidationError (/Users/vynguyen/shopping-cart/node_modules/mongoose/lib/error/validation.js:23:11)
    at model.Document.invalidate (/Users/vynguyen/shopping-cart/node_modules/mongoose/lib/document.js:1524:32)
    at /Users/vynguyen/shopping-cart/node_modules/mongoose/lib/document.js:1399:17
    at validate (/Users/vynguyen/shopping-cart/node_modules/mongoose/lib/schematype.js:706:7)
    at /Users/vynguyen/shopping-cart/node_modules/mongoose/lib/schematype.js:750:9
    at Array.forEach (native)
    at SchemaString.SchemaType.doValidate (/Users/vynguyen/shopping-cart/node_modules/mongoose/lib/schematype.js:711:19)
    at /Users/vynguyen/shopping-cart/node_modules/mongoose/lib/document.js:1397:9
    at _combinedTickCallback (internal/process/next_tick.js:67:7)
    at process._tickCallback (internal/process/next_tick.js:98:9)

This is my Mongoose schema:

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

var schema = new Schema({
    user: {type: Schema.Types.ObjectId, ref: 'User'},
    cart: {type: Object, required: true},
    address: {type: String, required: true},
    name: {type: String, required: true},
    paymentId: {type: String, required: true}
});

module.exports = mongoose.model('Order', schema);

This is my index.js:

var express = require('express');
var router = express.Router();
var Cart = require('../models/cart');

var Product = require('../models/product');
var Order = require('../models/order');

/* GET home page. */
router.get('/', function(req, res, next) {
    var successMsg = req.flash('success')[0];
    Product.find(function(err, docs) {
        var productChunks = [];
        var chunkSize = 3;
        for (var i = 0; i < docs.length; i += chunkSize) {
            productChunks.push(docs.slice(i, i + chunkSize));
        }
        res.render('shop/index', { title: 'Shopping Cart', products: productChunks, successMsg: successMsg, noMessages: !successMsg});
    });
});

router.get('/add-to-cart/:id', function(req, res, next) {
    var productId = req.params.id;
    var cart = new Cart(req.session.cart ? req.session.cart : {});

    Product.findById(productId, function(err, product){
        if (err) {
            return res.redirect('/');
        }
        cart.add(product, product.id);
        req.session.cart = cart;
        res.redirect('/');
    });
});

router.get('/shopping-cart', function(req, res, next) {
    if (!req.session.cart) {
        return res.render('shop/shopping-cart', {products: null});
    }
    var cart = new Cart(req.session.cart);
    res.render('shop/shopping-cart', {products: cart.generateArray(), totalPrice: cart.totalPrice});
});

router.get('/checkout', function(req, res, next) {
    if (!req.session.cart) {
        return res.redirect('/shopping-cart');
    }
    var cart = new Cart(req.session.cart);
    var errMsg = req.flash('error')[0];
    res.render('shop/checkout', {total: cart.totalPrice, errMsg: errMsg, noError: !errMsg});
});

router.post('/checkout', function(req, res, next) {
    if (!req.session.cart) {
        return res.redirect('/shopping-cart');
    }
    var cart = new Cart(req.session.cart);

    var stripe = require("stripe")(
      "**hidden**"
    );

    stripe.charges.create({
      amount: cart.totalPrice * 100,
      currency: "usd",
      source: req.body.stripeToken,
      description: "Test Charge"
    }, function(err, charge) {
        if (err) {
            req.flash('error', err.message);
            return res.redirect('/checkout');
        }
        var order = new Order({
            user: req.user,
            cart: cart,
            address: req.body.address,
            name: req.body.name,
            paymentId: charge.id
        });
        order.save(function(err, result) {
            req.flash('success', 'Successfully bought product!');
            req.session.cart = null;
            res.redirect('/');  
        });
    });
});

module.exports = router;

So, this is how I solved the error:

I consoled out every field inside the order object and found a syntax error in my checkout.form that is linked to req.body.address. After fixing the error 'order' is now showing in my db collections.

Phew! Kudos to israel.zinc for spending time chatting with me to get to the bottom of the issue.

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