【问题标题】:.save is not a function and .map is not a function while updating document.save 不是函数, .map 不是更新文档时的函数
【发布时间】:2020-04-20 16:54:05
【问题描述】:

我有以下代码:当我尝试从邮递员那里说:

"message": "account.save 不是函数"

const account = await Account.find({ "buildings.gateways.devices.verificationCode": code })
    var accountId = account ? account.map(item => item._id) : null

const buildings = _.flatMap(account, a => a.buildings)
const gateways = _.flatMap(buildings, b => b.gateways);
const devices = _.flatMap(gateways, g => g.devices);

// finding deviceId to insert for user from that account
const device = _.filter(devices, d => d.verificationCode === code);

device.patientFirstName = req.body.firstName;
device.patientLastName = req.body.lastName;
account.save();

如果我尝试更改为 findOne() 那么它会说

“account.map 不是函数”

帐户总是返回值,那么为什么它不能映射我不明白。

感谢您的帮助。谢谢

【问题讨论】:

    标签: javascript mongodb mongoose mongodb-query mongoose-schema


    【解决方案1】:

    .find() 返回一个数组,因此您可以运行Array.map(),但您需要分别.save() 每个文档:

    const accounts = await Account.find({ "buildings.gateways.devices.verificationCode": code })
    var accountId = account ? account.map(item => item._id) : null
    
    for(let account of accounts){
        await account.save();
    }
    

    .findOne()(等待)返回单个文档,因此您不能使用.map()

    const account = await Account.findOne({ "buildings.gateways.devices.verificationCode": code })
    var accountId = account ? account._id : null
    
    account.save();
    

    【讨论】:

      猜你喜欢
      • 2021-10-13
      • 2016-12-08
      • 1970-01-01
      • 2021-07-14
      • 2022-11-15
      • 2023-02-16
      • 1970-01-01
      • 2016-09-02
      • 2015-10-18
      相关资源
      最近更新 更多