无法将Mongoose中的JSON数据插入MongoDb

时间:2017-07-21 11:42:00

标签: mongodb mongoose

我正在尝试保留以下json数据,该文档是在Mongo中创建的,其id不带数据。

数据:

{
    "delivery": "{\"firstName\":\"John\",\"lastName\":\"Public\",\"email\":\"john@public.com\",\"phone\":\"5555555555\",\"shippingAddress\":\"40 Beauman Plaza\",\"city\":\"Anchorage\",\"state\":\"AK\",\"zip\":\"55555\",\"deliveryDate\":\"2017-07-29T04:00:00.000Z\",\"deliveryInstruction\":\"Deliver it today\"}",
    "payment": "{\"creditCardNo\":9898767876545432,\"creditCardYear\":\"2025\",\"creditCardMonth\":\"11\",\"cws\":\"111\",\"paymentType\":\"\"}",
    "orderProduct": "[{\"productId\":\"5962a568734d1d256343a213\",\"quantity\":1},{\"productId\":\"596161e1734d1d25634366ce\",\"quantity\":1},{\"productId\":\"5962a545734d1d256343a20e\",\"quantity\":1},{\"productId\":\"5962a5ac734d1d256343a221\",\"quantity\":1}]"
}

将数据插入Mongo的Mongoose代码:

  router.post('/order/add', function(req, res) {
  var order = req.body.order; 

  var newOrder = new Order({
    delivery: req.body.delivery,
    payment: req.body.payment,
    orderProduct: req.body.orderProduct        
  });
  newOrder.save(function(err) {
    if(err) {
        return res.status(500).json(err);
    }
    return res.status(200).json(newOrder);
  })    
})

在Mongo中创建的结果:

{
    "_id": {
        "$oid": "5971e49e777cab0f18456da9"
    },
    "orderProduct": [],
    "payment": [],
    "delivery": [],
    "__v": 0
}

猫鼬模型:

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

var DeliverySchema = new Schema({
  firstName: String,
  lastName: String,
  email: String,
  phone: String,
  shippingAddress: String,
  city: String,
  state: String,
  zip: String,
  deliveryDate: Date,
  deliveryInstruction: String});

var PaymentSchema = new Schema({
  creditCardNo: String,
  creditCardYear: String,
  creditCardMonth: String,
  cws: String,
  paymentType: String})

var OrderProductSchema = new Schema({
  productId: Number,
  quantity: Number});

var OrderSchema = new Schema({
  delivery: DeliverySchema,
  payment: PaymentSchema,
  orderProduct: [OrderProductSchema]});

var Order = mongoose.model("Order", OrderSchema, "order");
module.exports = Order;

对持久数据的角度调用:

placeOrder() {
  let orderData = new Order();
  orderData.delivery = JSON.stringify(this.deliveryForm.getRawValue());
  orderData.payment = JSON.stringify(this.paymentForm.getRawValue());
  orderData.orderProduct = this.cartService.getOrderProduct();
  var order = JSON.stringify(orderData);    
  console.log(order);
  this.checkoutService.placeOrder(order)
}

Http电话:

placeOrder(order) {
  this.http.post(this.orderUrl, {order: order})
  .toPromise()
  .then(res => console.log('result = ' + res.json().data as string))
  // .map((res: Response) => res.json())
  // .catch(this.handleError);
}

1 个答案:

答案 0 :(得分:0)

我认为,问题出在JSON.stringify。尝试将其从角度中删除,然后在快速控制器中以Content-type: 'application/json'JSON.parse发送。