javascript - 通过 id 在 schema 中搜索数组

标签 javascript mongodb

const FormFieldsSchema = new Schema({
  formName: {
    type: String,
    required: true
  },
  fields: [
    {
      fieldLabel: {
        type: String,
        required: true
      },
      inputData: [{
        type: mongoose.Schema.ObjectId,
        ref: "UserData"
      }]
    }
  ]
});

大家好,我有一个模式,其中 fields 是一个数组,现在对于每个数组项,我都有一个 _id 属性,我希望找到该数组并更新它,但我无法做到这一点, 我尝试了 findByIdAndUpdate,但它不起作用,还尝试了 parent.inputData.id(_id); 还没有运气,有什么想法吗?

最佳答案

将数组的内容转换为单独的模型,然后您可以直接查询该模型。

FormFieldsSchema上运行findByIdAndUpdate填充搜索FormFields_id而不是字段的内容 数组。

const FieldSchema = new Schema({
      fieldLabel: {
          type: String,
          required: true
      },
      inputData: [{
          type: mongoose.Schema.ObjectId,
        ref: "UserData"
      }]
})

并将field更改为fields: [FieldSchema] 另外,不要忘记将 FieldSchema 导出为模型。

关于javascript - 通过 id 在 schema 中搜索数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60476136/

相关文章:

typescript - 类型 '{ useNewUrlParser: boolean; useUnifiedTopology: boolean}' 的参数不可分配给类型的参数'

mysql - 跟踪用户事件日志 - SQL 与 NoSQL?

javascript - 在 Promise 中调用 setState 时 React Jest 测试失败

javascript - 如何使用导入的 JS 对象数组部署 REST API?

node.js - 为具有异构数组的对象创建 Mongoose 模式

node.js - MongoDB将相关的收集项目计数与其他收集结果合并

javascript - 如何在 JavaScript 中获取 html 实体的数字、十六进制和 ISO

javascript - jQuery :[] selector?

JavaScript。如何比较输入数组

node.js - 使用 Mongoose 获取所有数据库的列表