【问题标题】:MongoDB unable to push to array when grabbing schema by _idMongoDB 在通过 _id 获取模式时无法推送到数组
【发布时间】:2020-04-29 15:49:09
【问题描述】:

我一直在尝试向我的网站添加订阅功能,该人订阅该类,并将该类添加到用户模型中的类数组中...这是我的代码:

app.post("/subscribe", function (req, res) {
    const newClass = req.body.subClass;
    const id = req.user.id
    const ObjectId = mongoose.Types.ObjectId;
    User.findOneAndUpdate(
        { _id: new ObjectId(id) },
        { $push: { classes: newClass } },
        { upsert: false, new: true }
    );
    res.redirect("/dashboard")
});

这是我的架构:

const userSchema = new mongoose.Schema({
    email: String,
    password: String,
    secret: String,
    classes: [String]
});

以及我正在推动的模型: const User = new mongoose.model("User", userSchema)

感谢所有帮助

【问题讨论】:

  • 使用普通 id。 ``` User.findOneAndUpdate( { _id: id }, { $push: { classes: newClass } }, { upsert: false, new: true } ); ``` 或使用“findByIdAndUpdate”

标签: javascript node.js mongodb nosql


【解决方案1】:
app.post("/subscribe", async function (req, res) {
    try {
    const newClass = req.body.subClass;
    const id = req.user.id
    const ObjectId = mongoose.Types.ObjectId;
    await User.findByIdAndUpdate(
            id,       
            { $push: { classes: newClass } },
            {upsert: true, new: true }


   );
   }
   catch(err) {
    console.error(err);
   }
    res.redirect("/dashboard")

});

这里是猫鼬参考link

【讨论】:

  • 由于某种原因这也行不通...您认为这可能是数组为空的原因吗?我对猫鼬还不是很熟悉
  • 检查 newClass 值。放置调试器或控制台。使用 async await 和 try/catch 更新代码。
  • 使用 upsert: true。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-26
  • 2020-08-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-11-19
相关资源
最近更新 更多