如何使用 Mongoose 将元素推送到对象数组中?

时间:2021-03-12 06:20:28

标签: node.js mongodb mongoose

这是我的用户架构:

    const userSchema = mongoose.Schema({
      userid: String,
      username: String,
      pwd: String,
      login_devices: {
        type: Object,
        default: {
          currentDevice: "",
          devicesList: [],
        },
      },
    });

我的问题是:

  1. 如何将元素推送到 login_devices.devicesList 中?
  2. 我可以使用查询结果来构建模型吗?

感谢帮助

1 个答案:

答案 0 :(得分:0)

获取所需的文档并像在 javascript 对象中一样添加元素。然后使用 mongoose .save() 函数更新对象。

const user = await this.UserModel.find({});
user.login_devices.default.devicesList.push(new device);
return await user.save()
相关问题