我的数据没有被正确保存
这是我的架构
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)
};
这是我的发帖请求
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 newPurchase = new models.cartModel({
products: [
{
title,
colorC,
sizeC,
count,
date,
transactionID
}
]
});
const purchase = await newPurchase.save();
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"}
}
我希望数据看起来像这样
{
"_id": "5d439bc758a1f004b876bac3",
"products": [
{
"_id": "5d439bc758a1f004b876bac4",
"title": "COMME DES GARCONS TEE",
"colorC": null,
"sizeC": "Small",
"count": 1,
"date": "2019-07-29T06:08:07.000Z",
"transactionID": 1564380487732
}
],
"__v": 0
}
最佳答案
Mongoose 模式没有构造函数
new models.ProductSchema({ ...data })
会给你一个错误。
为此,您必须导出模式的模型
module.exports = {
cartModel: mongoose.model('Cart', CartSchema),
productModel: mongoose.model('Cart', ProductSchema),
}
现在你可以使用模型构造函数来实现你想要的
const newProduct = new models.cartModel({
colorC,
sizeC,
date,
title,
transactionID,
count
})
然后您就可以使用您的产品存储到您想要的任何地方
const newPurchase = new models.CartSchema({
products: [newProduct.toJSON()]
});
是的,您必须同时保存两者。
newProduct.save();
newPurchase.save();
关于mongodb - 我正在尝试使用请求创建一个新的购物车模式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57300657/