Mongoose没有将数据保存到mongodb?

时间:2017-03-07 05:05:25

标签: javascript node.js mongodb express

我正在使用JavaScript构建购物车,MongoDB& Node.js的我已经能够保存所有网站的产品,用户和到目前为止的会议完成我的结帐表单后,我的输入应保存到MongoDB。我应该能够在db集合中看到“订单”。但是当我在命令行中键入show collections时,只会显示产品,用户,会话

这是错误消息:

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)

这是我的Mongoose架构:

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);

这是我的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;

1 个答案:

答案 0 :(得分:0)

所以,这就是我解决错误的方法:

我安排了订单对象中的每个字段,并在checkout.form中发现了一个语法错误,该错误链接到req.body.address。修好错误后,订购&#39;现在显示在我的数据库集合中。

唷!感谢israel.zinc花时间与我聊天以解决问题的根源。