【问题标题】:Update Mongoose Array更新 Mongoose 数组
【发布时间】:2020-09-13 10:07:12
【问题描述】:

所以基本上我有这个,我正在尝试更新数组的STATUS 部分。 但是,我尝试的一切都无济于事。我也试过findOneAndUpdate。我试图通过数字识别数组中的特定项目,然后更新该特定数组的状态部分 (抱歉格式化,我还不知道如何在网站上这样做......)(可以在这里找到完整代码:https://sourceb.in/0811b5f805

代码

const ticketObj = {
  number: placeholderNumber,
  userID: message.author.id,
  message: m.content,
  status: 'unresolved'
}

let tnumber = parseInt(args[1])
let statuss = "In Progress"
await Mail.updateOne({
  "number": tnumber
}, { $set: { "status": statuss } })

架构

const mongoose = require('mongoose')

const mailSchema = new mongoose.Schema({
  guildID: { type: String, required: true },
  ticketCount: { type: Number, required: true },
  tickets: { type: Array, default: [] }
}, { timestamps: true });

module.exports = mongoose.model('Mail', mailSchema)

【问题讨论】:

  • 如果有错误是什么?
  • 没有错误。它只是不更新​​

标签: node.js mongodb mongoose discord.js


【解决方案1】:

你需要使用Mail.updateOne({"guildID": message.guild.id}, {$set: {`tickets.${tnumber}.status`: statuss}})之类的东西

或者对于数组中的所有对象:

Mail.updateOne({"guildID": message.guild.id}, {$set: {'tickets.$[].status': statuss}})

此外,您需要为tickets 创建一个架构,如docs 中所述:

one important reason to use subdocuments is to create a path where there would otherwise not be one to allow for validation over a group of fields

【讨论】:

  • 如何为多个对象执行此操作?这是我还没有尝试过的唯一原因......
  • Mongo 在数组中具有用于查询的特殊运算符。 docs.mongodb.com/manual/reference/operator/update/…
  • 没关系!拥有tickets.${tnumber}.status 会破坏一切,但由于某种原因,当它被 ` 但不是 ' 包围时
  • 可能你的js编译器不支持es5/es6特性,试试这个吧"tickets." + tnumber + ".status"
  • 不......它说它期待一个:现在大声笑之前它期待一个“财产分配”
猜你喜欢
  • 1970-01-01
  • 2017-01-24
  • 2019-03-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-12-12
  • 2022-01-22
相关资源
最近更新 更多