简体   繁体   English

尝试使用 Z758D31F351CE14BF27C522FZ 在 node.js 中从 POST API 中的 mongodb 集合中发布数组

[英]Trying to post array in my mongodb collection from POST API in node.js using mongoose and express

This is my orders model .这是我的订单 model

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

This is my products model这是我的产品 model

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

Now I want to post multiple products in single order post API call ;现在我想在 API 调用后以单个订单发布多个产品 Currently using this approach but this is not working for arrays.目前使用这种方法,但这不适用于 arrays。 How I can add multiple products just by sending multiple productIds in JSON format.如何仅通过以 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);

});

You have to think of it in modular terms and approach it step by step.您必须以模块化的方式考虑它并逐步处理它。

You are currently trying to do it all at once.您目前正在尝试一次完成所有操作。 Break it into bits.把它分成几块。

Mongoose has a method called populate(), which lets you reference documents in other collections. ZCCADCDEDB567ABAE643E15DCF0974E503Z 有一个名为 populate() 的方法,可以让您参考其他 collections 中的文档。

Population is the process of automatically replacing the specified paths in the document with document(s) from other collection(s).填充是自动将文档中的指定路径替换为其他集合中的文档的过程。 We may populate a single document, multiple documents, a plain object, multiple plain objects, or all objects returned from a query.我们可以填充单个文档、多个文档、普通 object、多个普通对象或从查询返回的所有对象。

Here is an example:这是一个例子:

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);

From the example you can see that you are not doing the right way as you have not set a reference between Order and Product.从示例中您可以看到您的方法不正确,因为您没有在 Order 和 Product 之间设置引用。

You order schema can set a reference to product like so:您订购的架构可以设置对产品的引用,如下所示:

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

The code above defines an association between the Order and Product database schemas.上面的代码定义了OrderProduct数据库模式之间的关联。 Like I mentioned in the beginning, you have to take a modular approach.就像我在开头提到的那样,您必须采用模块化方法。 From what I can see about your Project, you create Products first and then a customer creates an Order per Product.根据我对您的项目的了解,您首先创建产品,然后客户为每个产品创建一个订单。 You have to the create a Products.您必须创建一个产品。 When this is done, you can then reference a particular product by Id when you are creating an order.完成此操作后,您可以在创建订单时按 Id 引用特定产品。 Like so:像这样:

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

You can read more on Mongoose Populate method here.您可以在此处阅读有关 Mongoose 填充方法的更多信息。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 尝试使用猫鼬(NODE.JS)在mongoDB上发布 - Trying to post on mongoDB using mongoose (NODE.JS) 无法使用Node.js Express MongoDB Mongoose CoffeeScript进行POST - Cannot POST with Node.js Express MongoDB Mongoose CoffeeScript 我正在尝试使用 node.js 将一组对象发布到我的 mongodb - I'm trying to post an array of obejcts into my mongodb using node.js 尝试使用猫鼬更新mongodb中的记录。 我的应用程序正在使用Node.js和Express 4 - Trying to update record in mongodb using mongoose. My application is using Node.js and Express 4 router.post /使用Node JS,Express,Mongoose将嵌套数组添加到MongoDB数据库 - router.post / adding nested array to MongoDB database using Node JS, express, mongoose node.js mongodb express-无法发布/ - node.js mongodb express - cannot POST/ 使用Node.js,Express和MongoDB .post()错误创建Rest API - Creating Rest API using Node.js, Express, and MongoDB .post() error javascript node.js从mongoose mongodb获取消息/变量,将钩子传递到express.js中的钩子传递之前 - javascript node.js get a message/variable from mongoose mongodb pre hook into post hook in express.js 如何使用 NODE.js 和 Express 将 MongoDB 数据发布到嵌套数组 - How to post MongoDB data to the nested array using NODE.js and Express 如何使用Node.Js,MongoDB,Mongoose,Express对博客帖子(已登录和未登录的用户)的唯一视图计数 - How to count unique views to a blog post (logged in and non logged in user) using Node.Js, MongoDB, Mongoose, Express
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM