【问题标题】:How to insert data in array field in Mongodb using mongoose and NodeJs如何使用 mongoose 和 NodeJs 在 Mongodb 的数组字段中插入数据
【发布时间】:2021-11-25 02:21:08
【问题描述】:

我想在 mongodb 中插入数据,其中一个字段是对象类型的数组。我无法了解如何将数据与 mongoose 模式中定义的其他字段一起添加到数组字段中。当我尝试使用具有以下配置的 POSTMAN 发布数据时,如屏幕截图所示:

它的显示游戏数组是空的并且显示下面的错误

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

下面是我的代码:

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

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;

可以按照下面的代码插入两个字段,但是如何添加数组字段以及这两个字段。

server.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}`));

请告诉我如何执行此任务。

【问题讨论】:

  • 与其他2个字段相同,只需将第三个数组字段与其他字段一起传递即可。
  • 我试过了,但它没有插入到数组字段中。我已经在我的帖子中附上了 POSTMAN 的屏幕截图。
  • 您没有在实际代码new publisher({company_name,website}); 中传递该字段,其次邮递员请求数组字段的值为字符串,更改键名games[0] 并在请求中添加新字段并增加索引以获取更多索引。
  • 你从邮递员那里传错了游戏数组,像this一样传。同样正如@turivishal 所说,解构控制器中的游戏属性并将其放入 Publisher 构造函数中。
  • 它在解构游戏值后显示此错误并将其添加为一个字段`游戏:CastError: Cast to embedded failed for value "'San and'" (type string) at path "games"`

标签: node.js mongodb mongoose mongoose-schema


【解决方案1】:

您得到的是CastError,因为 mongodb 只接收 games 数组架构字段类型的字符串“San and”。

在 Postman 中,您需要将 games key 更改为 games[0][name] 才能传递“San and”作为游戏名称。 @turivishal 和 @KunalMukherjee 在原始 cmets 中都提到了这一点。要添加其他数组项,您可以在 Postman 中这样做,使用 x-www-form-urlencoded

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

或者,您可以通过选择raw 帖子正文输入方法而不是x-www-form-urlencoded 直接编写JSON。像这样:

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

这是我使用这种方法在 PostMan 中得到的输出:

以及 MongoDB 中的 DB 文档:

这是带有工作代码的 github 存储库:https://github.com/angusryer/mongo-play

您必须将 mongodb uri 指向您自己的 Cloud Atlas 或本地服务器实例。通过these steps here 设置 Cloud Atlas。


在更新问题之前,您似乎忘记了从 req.body 中的 server.js 中提取游戏数组:

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

【讨论】:

  • 在执行您的解决方案时显示此错误`游戏:CastError: Cast to embedded failed for value "'San and'" (type string) at path "games"`
  • 很晚了,但为了后代,我已经更新了答案。
  • 它不工作的数组仍然是空的
  • 这很奇怪。在我第一次发送这个 POST 请求时,mongo db 由于某种原因没有收到数组。这可能是我的缓存错误 - 不确定。无论哪种方式,每个后续的 POST did 都表现正常,所以我更新了我的答案以显示我得到的结果。我相信这回答了最初的问题。如果它仍然无法正常工作并且您拥有上述所有代码,那么可能还有另一个问题。
猜你喜欢
  • 2018-06-22
  • 2019-01-11
  • 2016-08-16
  • 2019-02-01
  • 1970-01-01
  • 2021-10-04
  • 2016-04-01
  • 1970-01-01
  • 2017-08-29
相关资源
最近更新 更多