【问题标题】:I'm trying to post an array of obejcts into my mongodb using node.js我正在尝试使用 node.js 将一组对象发布到我的 mongodb
【发布时间】:2023-01-08 22:39:37
【问题描述】:

我正在尝试使用我的 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({obj});

  newItems.save()
    .then(() => res.json('User added!'))
    .catch(err => res.status(400).json('Error: ' + err));
});

module.exports = router;

但是有些当我运行它时它只是返回一个空数组

发布数据

   {
        "_id": "90bacff0cc5c2e3734545f34",
        "item": [],
        "__v": 0
    }

【问题讨论】:

    标签: node.js arrays mongodb express mongoose


    【解决方案1】:

    您的架构是这样的:

    const LevelSchema = new Schema({
        item: [Object],
    });
    

    所以你必须插入类似的东西:

    {
      item: [{}]
    }
    

    但是你要插入:

    {
      obj: [{}]
    }
    

    所以使用 const newItems = new Items({item:obj}); 应该可以。

    【讨论】:

      猜你喜欢
      • 2020-09-26
      • 1970-01-01
      • 2020-10-13
      • 2020-04-11
      • 2021-02-03
      • 1970-01-01
      • 2016-04-02
      • 1970-01-01
      • 2020-05-01
      相关资源
      最近更新 更多