使用 nodejs 和 mongoDB, 如何在产品数组中添加产品对象?
****我正在尝试嵌套..下面提到的代码**** 类别架构
const mongoose = require("mongoose")
const category = new mongoose.Schema({
name: { type: String, required: true, unique: true },
slug: { type: String, required: true },
sub: []
}, {
collection: "Categories", timestamps: true
})
const model = mongoose.model("category", category);
module.exports = model
使用这个模式(上面提到过)我将子类别添加到 sub[]
router.post('/addcategory', async (req, res)=>{
const category = new Category({
name: req.body.cat_name.trim(),
slug: req.body.cat_slug.trim()
})
category.save()
.then(()=>{
router.post('/addsubcategory', async (req, res) => {
let name= req.body.subcat_name.trim();
let slug= req.body.subcat_slug.trim();
let category = req.body.selectcategory.trim();
Category.updateOne({"name": category},
{
$push: {
sub: {$each: [{name: name, slug: slug, products: []}]}
}
})
.then(()=>{
直到这里它工作正常
问题从这里开始
router.post('/addproduct', async (req, res) => {
let name= req.body.prod_name.trim();
let price= req.body.prod_price.trim();
let category = req.body.selectcategory.trim();
let subcategory = req.body.selectsubcategory.trim();
let desc = req.body.prod_desc.trim();
console.log(`Collection: ${name+""+price+""+category+""+subcategory+""+desc}`)
Category.updateOne({"name": "category", "sub.name": "subcategory"},
{
$push: {
"sub.$[].products": {$each: [{name, price, desc}]}
// products: {$each: [{name, price, desc}]} This didnt work too.
}
})
.then(()=>{
[Unable to add product in product array][4]
我无法在 products[] 中添加产品集合名称:类别
如何在产品数组中添加产品对象? 这是我的数据库在插入时的样子
{"_id":{"$oid":"61fa651c844869aae2cacdcd"},
"name":"Clothes","slug":"clothes","sub":[
{"name":"Sports","slug":"sports","products":[]},
{"name":"Party wear","slug":"partywear","products":[]}
],
"createdAt":{"$date":{"$numberLong":"1643799836133"}},
"updatedAt":{"$date":{"$numberLong":"1643800511218"}},
"__v":{"$numberInt":"0"}}