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

发布于 2025-01-15 13:37:13 字数 2750 浏览 1 评论 0原文

我使用 node.js 连接到我的数据库。 现在我想将一些数据发送到数据库,如下所示:

数据

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.
}

我的架构描述为:

Schema.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;

我的数据控制器是:

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

应用程序已成功连接到数据库。但是当我向数据库发送数据时,它总是显示 错误:来自服务控制器 E11000 重复密钥错误集合:HouseDeck-Cluster.services index: services_1 dup key: { services: null }

我使用 console.log() 检查了这一点正如您在 controller.js 中看到的那样。当我显示数据时,它显示数据是正确的,但是当我执行 console.log(newService) 时。 它总是显示 { _id: new ObjectId("6234720c80a5f440ade88d24"), service: [] }

它表明架构有问题。我尝试了各种方法,例如:

已经尝试过这些架构

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 am connected to my database using node.js.
Now I want to send some data to the database which is as follows:

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

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.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 }

I checked for that by using console.log() as you can see in controller.js. When I am displaying the data it shows the data is correct but when I do console.log(newService).
It always shows
{ _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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

柠栀 2025-01-22 13:37:13

您已在架构中指出所有字段都是唯一的。

因此,您在所有字段中插入的所有数据必须是唯一的。

尝试像这样修改您的架构:

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

然后插入您的数据,如下所示:

newService.insertMany(service);

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);
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文