[英]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.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.