简体   繁体   English

使用 node.js 将对象数组发送到 MongoDB Atlas

[英]Sending Array of Objects to MongoDB Atlas using node.js

I am connected to my database using node.js. Now I want to send some data to the database which is as follows:我使用 node.js 连接到我的数据库。现在我想向数据库发送一些数据,如下所示:

data数据

const service=[
    {ServiceChoseByUser:'Cleaning',PriceForService:'100'},
    {ServiceChoseByUser:'Painting',PriceForService:'300'},
    {ServiceChoseByUser:'Electrician',PriceForService:'400'},
    {ServiceChoseByUser:'Plumbing',PriceForService:'50'},
    // may be increased as the number of services selected by the user.
}

My schema is described as:我的模式被描述为:

Schema.js架构.js

import mongoose from 'mongoose';

const serviceSchema = new mongoose.Schema({
    service: [
        {
            id: {
                  type: String,
                  trim: true,
                  unique: true
            },
            ServiceChoseByUser: {
                  type: String,
                  trim: true,
                  unique: true,
                  lowercase:true
            },
            PriceForService: {
                  type: String,
                  trim: true,
                  lowercase:true,
                  unique: true,
           },
       },
    ]
});

let Service = mongoose.model('service', serviceSchema);

export default Service;

And my controller of data is:而我的 controller 的数据是:

controller.js controller.js

import Service from ".Schema.js";


export const sendService = async (req, res) => {
    try {
        const serviceByUser = req.body;
        console.log(serviceByUser);
        const newService = new Service(service);
        console.log(newService);
        await newService.save();
        console.log('Service data stored');
        res.send(200 + 'Service data stored')
    } catch (error) {
        res.send(500 + ' Error occured');
        console.log('Error: from service controller ', error.message);
    }
}

The app is connected successfully to the database.该应用程序已成功连接到数据库。 But when I am sending data to the database, it always shows Error: from service controller E11000 duplicate key error collection: HouseDeck-Cluster.services index: services_1 dup key: { services: null }但是当我向数据库发送数据时,它总是显示Error: from service controller E11000 duplicate key error collection: HouseDeck-Cluster.services index: services_1 dup key: { services: null }

I checked for that by using console.log() as you can see in controller.js .正如您在controller.js中看到的那样,我使用console.log()检查了这一点。 When I am displaying the data it shows the data is correct but when I do console.log(newService) .当我显示数据时,它显示数据是正确的,但是当我显示console.log(newService)时。 It always shows { _id: new ObjectId("6234720c80a5f440ade88d24"), service: [] }它总是显示{ _id: new ObjectId("6234720c80a5f440ade88d24"), service: [] }

It states that something is wrong with the schema.它指出架构有问题。 I tried various things like:我尝试了各种事情,例如:

Already Tried These For Schema已经为架构尝试过这些

1. service=[Object]

2. service=[
       {
          id:String,
          ServiceChoseByUser:String,
          PriceForService:String
       }
    ]
 
3. service=Array

4. service={
      type:Array
     }

5. service=[
      {
          type:Object
      }
   ]

6. // already provided above

I tried many things, also searched for it, read the documentation but I couldn't find any solution.我尝试了很多东西,也进行了搜索,阅读了文档,但找不到任何解决方案。

Please help请帮忙

You have indicate in your schema that all fields are unique.您已在架构中指出所有字段都是唯一的。

So, all data you insert in all fields must be unique.因此,您在所有字段中插入的所有数据都必须是唯一的。

Try modifying your schema like this:尝试像这样修改您的模式:

const serviceSchema = new mongoose.Schema({
            id: {
                  type: String,
                  trim: true,
                  unique: true
            },
            ServiceChoseByUser: {
                  type: String,
                  trim: true,
                  lowercase:true
            },
            PriceForService: {
                  type: String,
                  trim: true,
                  lowercase:true
           }
});

And then insert your datas with something like this:然后用这样的东西插入你的数据:

newService.insertMany(service);

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM