簡體   English   中英

mongoose 數組以錯誤的順序保存或如果定義了數組的架構,則會出現錯誤“轉換為字符串失敗的值”

[英]mongoose array saved in wrong order or got error 'Cast to string failed for value' if schema for array is defined

我正在開發一個生產力應用程序,其功能是人們可以從預定義的項目(任務)列表中選擇幾個項目來構建一組個人日常任務,並可選擇填寫一個輸入字段來修改該選定任務的持續時間。 在我的“用戶”mongoose 模式中,我有“任務”數組,當用戶完成他/她的任務選擇時,他/她的任務列表將保存在他的用戶詳細信息下,默認列表不會被修改。 我的問題是,當用戶選擇一些任務並單擊“保存今天的任務”時,帶有所選對象的數組“任務”保存在數據庫中,而是為每個 object 保存鍵/值對,我的應用程序將鍵保存在一個數組中object 和其他 object 中的值。 這是保存數據的示例:

// if defined in userSchema: 
// tasks: [] // just empty array

// what i get now:
"tasks": [
    {
      "title": [
        "Title 01",
        "Title 02",
      ],
      "duration": [
        10,
        20,
      ]
    }
  ]


// what i need:
"tasks": [
    {
      "title": "Title 01",
      "duration": 10
    },{
      "title": "Title 02",
      "duration": 20
    }
  ]

// if defined in userSchema: 
// tasks: [tasksSchema] // array of predefinied objects
// i got just error message
"error": {
    "message": "Cast to string failed for value \"[ 'Title 01', 'Title 02' ]\" at path \"title\"",
    "name": "CastError",
    "stringValue": "\"[ 'Title 01', 'Title 02' ]\"",
    "value": [
      "Title 01",
      "Title 02"
    ],
    "path": "title",
    "reason": null
  }

這是我的代碼的 rest(型號,controller,查看):

// my model
const tasksSchema = new mongoose.Schema({
  _id: {
    type: mongoose.Schema.ObjectId,
    ref: 'Tasks',
  },
  title: {
    type: String,
  },
  duration: {
    type: Number,
  },
});


const userSchema = new mongoose.Schema(
  {
    title: {
      type: String,
      trim: true,
      required: true,
    },
    tasks: [tasksSchema],
  }
  {
    timestamps: true,
  });

  module.exports = mongoose.model('User', userSchema);

// my controller
exports.updateUser = async (req, res, next) => {
  try {
    const user = await User.findOne({ _id: req.params.id });

    await User.findOneAndUpdate(
      { _id: req.params.id },
      req.body,
      { new: true, runValidators: true },
    ).exec();

    if (!user) {
      return res.status(404).json({
        success: false,
        error: 'no User found',
      });
    }

    return res.redirect('back');
  } catch (err) {
    if (err.name === 'ValidationError') {
      const messages = Object.values(err.errors).map((val) => val.message);
      return res.status(400).json({
        success: false,
        error: messages,
      });
    }
    return res.status(500).json({
      success: false,
      error: err,
    });
  }
};


// my view (pug/jade)
each item in user.tasksList || [] // this list is generated from a model 'Tasks'
  li.sortableItem.ui-state-default.list-group-item(value=item._id id=`id_${item._id}` name="tasks")
    span
      input#title(type='text' name="tasks[title]" value=item.title)
    span 
      input#duration.col-sm-2.input-sm.text-gray(type='number', name="tasks[duration]" value=item.duration)

我究竟做錯了什么? 很多thnx!

如果框架沒有簡單的方法將這些輸入作為對象數組返回,您可以在實例化用戶之前使用map從單獨的 arrays 創建對象數組:

tasks = tasks[0].title.map((e,i) => ({"title":e,"duration":tasks[0].duration[i]}))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM