简体   繁体   English

如何使用 mongoose 和 NodeJs 在 Mongodb 的数组字段中插入数据

[英]How to insert data in array field in Mongodb using mongoose and NodeJs

I want to insert data in mongodb where one field is of array of an objects type.I am unable to get how I can add data into array field along with other fields defined in mongoose schema.我想在 mongodb 中插入数据,其中一个字段是对象类型的数组。我无法了解如何将数据与 mongoose 模式中定义的其他字段一起添加到数组字段中。 When I am trying to post data using POSTMAN with below configurations as shown in screenshot:当我尝试使用具有以下配置的 POSTMAN 发布数据时,如屏幕截图所示:

Its showing games array is empty and showing below error它的显示游戏数组为空并显示以下错误

 games: CastError: Cast to embedded failed for value "'San and'" (type string) at path "games"

在此处输入图片说明

Below is my code:下面是我的代码:

db.js数据库.js

const mongoose = require('mongoose');
const dotEnv = require('dotenv').config();

const uri = process.env.URI;

const connect = mongoose.connect(uri,{useNewUrlParser:true,useUnifiedTopology:true})
                .then(() => console.log("Database connected"))
                .catch((err) => {
                   console.log("Something went wrong",err);
                   process.exit(1);
               });

module.exports = connect; 

publisher.js发布者.js

const mongoose = require('mongoose');

const publisherSchema = new mongoose.Schema({

  company_name:{
    type: String
  },
  website:{
    type: String
  }
  games: [{
    date: Date,
    name: String
   }]

 });

const publisher = mongoose.model('Publisher',publisherSchema);
module.exports = publisher;

Two fields can be inserted as given in below code but How Can I add array field along with these two fields.可以插入两个字段,如下面的代码所示,但如何添加数组字段以及这两个字段。

server.js服务器.js

const express = require('express');
const connect = require('./db.js');
const publisher = require('./models/publisher.js');
const gaming = require('./models/game.js');

const app = express();

const port = process.env.PORT || 3000;

app.use(express.json());
app.use(express.urlencoded({ extended: true }))

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

const { company_name,website,games } = req.body;

const insert = new publisher({company_name,website,games});

try{
    const data = await insert.save();
    res.send(data); 
}
catch(err){
    console.log(err);
}

});

app.listen(port, () => console.log(`App is up and runnning at ${port}`));

Someone let me know how can I perform this task.有人让我知道如何执行此任务。

You're getting the CastError because mongodb is only receiving the string "San and" for the games array schema field type.您收到CastError是因为 mongodb 只接收games数组架构字段类型的字符串“San and”。

In Postman, you need to change the games key to games[0][name] to be able to pass "San and" as the game's name.在 Postman 中,您需要将games更改为games[0][name]才能将“San and”作为游戏名称传递。 @turivishal and @KunalMukherjee both mention this in the original comments. @turivishal 和 @KunalMukherjee 都在原始评论中提到了这一点。 To add additional array items, you can do so like this in Postman, using x-www-form-urlencoded :要添加其他数组项,您可以在 Postman 中使用x-www-form-urlencoded

key: games[0][name] value: San and键: games[0][name]值: San and
key: games[0][date] value: 2020-01-01键: games[0][date]值: 2020-01-01
key: games[1][name] value: The Great Game键: games[1][name]值: The Great Game
key: games[1][date] value: 2020-01-02键: games[1][date]值: 2020-01-02
etc...等等...

Alternatively , you can write the JSON directly by selecting the raw post body entry method instead of x-www-form-urlencoded .或者,您可以通过选择raw帖子正文输入方法而不是x-www-form-urlencoded来直接编写 JSON。 Like this:像这样:

{
    "company_name": "roveo",
    "website": "www.ro.com",
    "games": [
        {
            "date": "2020-01-01",
            "name": "San and"
        },
        {
            "date": "2020-01-02",
            "name": "The Great Game"
        }
    ]
}

Before the question was updated, it looks like like you'd forgotten to extract the games array from your req.body in server.js as well:在问题更新之前,您似乎忘记从server.jsreq.body中提取游戏数组:

const { company_name, website, games } = req.body; // <-- missed `games`

const insert = new publisher({company_name, website, games}); // <-- and `games` here too

try{
    const data = await insert.save();
    res.send(data); 
}
catch(err){
    console.log(err);
}

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

相关问题 使用mongoose,nodejs将文档插入mongodb数组 - insert document into mongodb array using mongoose, nodejs 如何在nodejs中使用mongoose将对象数组和嵌套对象数组插入mongodb - how to insert array of objects and array of nested objects into mongodb using mongoose in nodejs 如何使用Mongoose在MongoDB中插入JSON数组 - How to insert an array of JSON in MongoDB using Mongoose 如何使用body-parser使用nodejs和mongoose将嵌套对象数组插入/添加到mongodb数据库中 - How to insert/add array of nested objects into mongodb database with nodejs and mongoose using body-parser 如何在打字稿中使用猫鼬在mongodb中插入数据 - How to insert data in mongodb using mongoose in typescript 如何使用猫鼬在nodejs中保存数组数据? - How to save array data in nodejs using mongoose? mongodb mongoose nodejs express4为什么在对象数组字段中自动插入_id? - mongodb mongoose nodejs express4 why insert a _id in Object Array field automatically? 如何使用Mongoose和NodeJS在MongoDB中保存嵌套数组 - How to save nested array in MongoDB using Mongoose and NodeJS 如何使用 mongoose、nodejs 从 Mongodb 获取数据 - How can i get data from Mongodb using mongoose, nodejs 如何使用nodejs和mongoose从mongodb集合中删除数据 - How to remove data from mongodb collection using nodejs and mongoose
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM