[英]How to insert data in array field in Mongodb using mongoose and NodeJs
我想在 mongodb 中插入数据,其中一个字段是对象类型的数组。我无法了解如何将数据与 mongoose 模式中定义的其他字段一起添加到数组字段中。 当我尝试使用具有以下配置的 POSTMAN 发布数据时,如屏幕截图所示:
它的显示游戏数组为空并显示以下错误
games: CastError: Cast to embedded failed for value "'San and'" (type string) at path "games"
下面是我的代码:
数据库.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;
发布者.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;
可以插入两个字段,如下面的代码所示,但如何添加数组字段以及这两个字段。
服务器.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}`));
有人让我知道如何执行此任务。
您收到CastError
是因为 mongodb 只接收games
数组架构字段类型的字符串“San and”。
在 Postman 中,您需要将games
键更改为games[0][name]
才能将“San and”作为游戏名称传递。 @turivishal 和 @KunalMukherjee 都在原始评论中提到了这一点。 要添加其他数组项,您可以在 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"
}
]
}
在问题更新之前,您似乎忘记从server.js
的req.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.