【问题标题】:Unable to update properties in mongoose object using nestjs无法使用nestjs更新猫鼬对象中的属性
【发布时间】:2021-10-02 08:53:01
【问题描述】:

不知何故,我无法更新从 MongoDB 获取的 mongoose 对象的属性。我正在尝试遵循这种模式:Mongoose Docs: Document

这是我的代码:

// note: getInstances just returns model.find()
let instances: InstanceDocument[] = await this.instanceService.getInstances();
instances.forEach(async (instance, index) => {
    console.log(instance);
    let deviceCount = await this.instanceService.getDeviceCount(instance._id);
    let elementCount = await this.instanceService.getElementCount(instance._id)
    instance.deviceCount = deviceCount;
    instance.elementCount = elementCount;
    await instance.save();
    console.log(deviceCount, elementCount, instance);
})

console.logdeviceCountelementCount 打印正确的值,但实例对象保持不变。它仍然具有数据库中未更新的值。

注意:这不是Unable to add properties to js object 的重复条目,因为我不是要创建新对象并为其赋予属性。

【问题讨论】:

    标签: javascript typescript mongodb mongoose nestjs


    【解决方案1】:

    两件事:

    1. 您不能在forEachmap 等数组方法中使用await。它doesn't work(不等待)。请改用for 循环。

    2. Mongoose 有一个奇怪的要求,您必须明确告诉它嵌套键已被修改才能保存它。见this question

    let instances: InstanceDocument[] = await this.instanceService.getInstances();
    
    for(let instance of instances) {
        console.log(instance);
        instance.deviceCount = await this.instanceService.getDeviceCount(instance._id);
        instance.elementCount = await this.instanceService.getElementCount(instance._id);
    
        instance.markModified("deviceCount"); // this
        instance.markModified("elementCount"); // and this
    
        await instance.save();
        console.log(deviceCount, elementCount, instance);
    }
    

    【讨论】:

      【解决方案2】:

      上面的代码有效。我在定义对象模式时犯了一个错误。我错过了我添加的属性的 @Prop() 装饰器。此代码有效:

      let instances: InstanceDocument[] = await this.instanceService.getInstances();
      let fetchingDone = new Subject();
      fetchingDone.subscribe(instances => res.json(instances))
      
      instances.forEach(async (instance, index) => {
        instance.deviceCount = await this.instanceService.getDeviceCount(instance._id);
        instance.elementCount = await this.instanceService.getElementCount(instance._id);
        await instance.save();
        if (index+1 === instances.length) fetchingDone.next(instances);
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-05-08
        • 2016-03-20
        • 2012-11-02
        • 2021-07-05
        • 2020-12-22
        • 2021-06-07
        • 1970-01-01
        • 2017-10-23
        相关资源
        最近更新 更多