英文:
I'm trying to post an array of obejcts into my mongodb using node.js
问题
我试图使用名为obj
的虚拟数据将对象数组发布到我的MongoDB,但它只发布了一个空数组。
这是我的代码:
模式
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const LevelSchema = new Schema({
item: [Object],
});
const Items = mongoose.model('items', LevelSchema);
module.exports = Items;
发布路由
const router = require('express').Router();
let Items = require('../models/items.modal');
router.route('/add').post((req, res) => {
const obj = [
{
"name":"name1"
},
{
"name":"name2"
},
{
"name":"name3"
}
];
const newItems = new Items({item: obj});
newItems.save()
.then(() => res.json('User added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router;
但不知何故,当我运行它时,它只返回一个空数组。
发布的数据
{
"_id": "90bacff0cc5c2e3734545f34",
"item": [],
"__v": 0
}
英文:
I'm trying to post an array of objects into my mongodb using my obj
dummy data, but it just posts an empty array instead
Here's my code
Schema
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const LevelSchema = new Schema({
item: [Object],
});
const Items = mongoose.model('items', LevelSchema);
module.exports = Items;
Post routes
const router = require('express').Router();
let Items = require('../models/items.modal');
router.route('/add').post((req, res) => {
const obj = [
{
"name":"name1"
},
{
"name":"name2"
},
{
"name":"name3"
}
]
const newItems = new Items({obj});
newItems.save()
.then(() => res.json('User added!'))
.catch(err => res.status(400).json('Error: ' + err));
});
module.exports = router;
But some how it just returns an empty array when I run it
Posted Data
{
"_id": "90bacff0cc5c2e3734545f34",
"item": [],
"__v": 0
}
答案1
得分: 2
你的模式如下:
const LevelSchema = new Schema({
item: [Object],
});
所以你需要插入类似这样的内容:
{
item: [{}]
}
但你正在插入:
{
obj: [{}]
}
所以使用 const newItems = new Items({item:obj});
应该可以工作。
英文:
Your schema is like this:
const LevelSchema = new Schema({
item: [Object],
});
So you have to insert something like:
{
item: [{}]
}
But you are inserting:
{
obj: [{}]
}
So using const newItems = new Items({item:obj});
should works.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论