【发布时间】:2019-12-10 13:14:08
【问题描述】:
当我将数据保存到数组中的数据库时,它不起作用,但是当我只发送一个对象时,它被正确存储。也许我的架构不正确?
这是我的架构
const mongoose = require('mongoose');
const ProductSchema = mongoose.Schema({
colorC: String,
sizeC: String,
date: Date,
title: String,
transactionID: Number,
count: Number
});
const CartSchema = mongoose.Schema({
products: [ProductSchema]
});
const Cart = mongoose.model('Cart', CartSchema);
module.exports = {
cartModel: mongoose.model('Cart', CartSchema),
productModel: mongoose.model('Product', ProductSchema)
};
this is my post request
const express = require('express');
const Cart = require('../models/Cart');
const models = require('../models/Cart');
const router = express.Router();
router.post('/', async (req, res) => {
const { colorC, sizeC, date, title, transactionID, count } = req.body;
try {
const newProduct = new models.productModel({
colorC,
sizeC,
date,
title,
transactionID,
count
});
const newPurchase = new models.cartModel({
products: [newProduct.toJSON()]
});
await newProduct.save();
await newPurchase.save()
const products = newProduct;
const purchase = newPurchase + products;
res.json(purchase);
} catch (err) {
console.error(err.message);
res.status(500).send('Server Error');
}
});
module.exports = router;
当我将数据作为包含两个对象的数组发送时,没有任何数据显示,例如,这应该显示我输入的对象。当我发送这个时,服务器不会在数组中保存任何产品。
[{
"colorC": null,
"count": 1,
"date": "Mon Jul 29 2019 02:08:07 GMT-0400 (Eastern Daylight Time)",
"sizeC": "Small",
"title": "COMME DES GARCONS TEE",
"transactionID": 1564380487732
},{
"colorC": null,
"count": 1,
"date": "Mon Jul 29 2019 02:08:07 GMT-0400 (Eastern Daylight Time)",
"sizeC": "Small",
"title": "COMME DES GARCONS TEE",
"transactionID": 1564380487732
}]
这是保存在数据库中的数据
{
"_id":{"$oid":"5d42ab9f4ec81021f0136e95"},
"products":[{"_id":{"$oid":"5d42ab9f4ec81021f0136e94"}}]
,"__v":{"$numberInt":"0"}
}
【问题讨论】:
-
因为 toJson 不是你想的那样,它只是返回属性而不是模型数据。
标签: database mongodb mongoose schema mern