【问题标题】:Trying to post array in my mongodb collection from POST API in node.js using mongoose and express尝试使用 mongoose 和 express 从 node.js 中的 POST API 将数组发布到我的 mongodb 集合中
【发布时间】:2020-09-26 18:13:48
【问题描述】:

这是我的订单模型

const Order = mongoose.model('Order', new mongoose.Schema({
    saleprice: {type: Number},
    discount: {type: Number},
    products : [{
        type: productSchema
    }]
}));

这是我的产品模型

const productSchema = new mongoose.Schema({
    name: {type: String, required: true},
    price: {type: Number, required: true},
    category: {type: String, required: true}
});

现在我想在单个订单发布 API 调用中发布多个产品;目前使用这种方法,但这不适用于数组。如何仅通过以 JSON 格式发送多个 productId 来添加多个产品。

router.post('/', async(req, res) =>{

    const product = await Product.findById(req.body.productId);
    if(!product) 
        return res.status(400).send('Invalid product.');

    const order =new Order({        
        saleprice: "790",
        discount: "100",
        products: [{
            _id: product._id,
            name: product.name,
            price: (product.price).toString(),
            category: product.category
        }]
    });
    await order.save();
    res.send(order);

});

【问题讨论】:

  • 你能把console.log(req.body) 放在你的Product.findById 上面,然后给我们看看输出吗?
  • *console.log(req.body.productId)
  • console.log(req.body.productId); = 5edc2a837c429c1f647ac6f5 Product.findbyID 之前执行此操作将显示通过我们的 JSON 提供的 ID { "productId": "5edc2a837c429c1f647ac6f5" }

标签: node.js json mongodb express mongoose


【解决方案1】:

您必须以模块化的方式来考虑它并逐步处理它。

您目前正尝试一次完成所有操作。把它分解成小块。

Mongoose 有一个名为 populate() 的方法,可以让您引用其他集合中的文档。

填充是自动将文档中的指定路径替换为其他集合中的文档的过程。我们可以填充单个文档、多个文档、一个普通对象、多个普通对象或从查询返回的所有对象。

这是一个例子:

const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const personSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: String,
  age: Number,
  stories: [{ type: Schema.Types.ObjectId, ref: 'Story' }]
});

const Person = mongoose.model('Person', personSchema);
const mongoose = require('mongoose');
const Schema = mongoose.Schema;

const storySchema = Schema({
  author: { type: Schema.Types.ObjectId, ref: 'Person' },
  title: String,
  fans: [{ type: Schema.Types.ObjectId, ref: 'Person' }]
});

const Story = mongoose.model('Story', storySchema);

从示例中您可以看出,您没有在 Order 和 Product 之间设置引用,因此您的方法不正确。

您的订单架构可以像这样设置对产品的引用:

...
products : [{
        type: Schema.Types.ObjectId, ref: 'Product'
    }]
...

上面的代码定义了 OrderProduct 数据库模式之间的关联。就像我在开头提到的那样,您必须采用模块化方法。根据我对您的项目的了解,您首先创建产品,然后客户为每个产品创建一个订单。您必须创建一个产品。完成此操作后,您可以在创建订单时按 Id 引用特定产品。像这样:

...
const order =new Order({        
        saleprice: "790",
        discount: "100",
        products: req.body.productId
    });
...

你可以阅读更多关于猫鼬填充方法here.

【讨论】:

  • 我无法在我的 POST API 中使用populate() 在一个订单中填充许多产品。你能写任何例子让我更好地理解吗?
  • 没关系。我将创建一个 github gist 并与您分享。
  • 将不胜感激。
猜你喜欢
  • 2020-01-19
  • 2023-01-08
  • 2011-12-07
  • 2019-04-26
  • 2014-02-10
  • 2015-05-28
  • 2015-06-30
  • 1970-01-01
  • 2016-12-27
相关资源
最近更新 更多