Search code examples
javascriptmongodbmongoosemongodb-querymongoose-schema

.save is not a function and .map is not a function while updating document


I have below code: When I try to from postman it says :

"message": "account.save is not a function"

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();

If I try to change to findOne() then it says

"account.map is not a function"

account always returns values then why it cant map i dont understand.

Your help is appreciated. Thanks


Solution

  • .find() returns an array so you're able to run Array.map() but you need to .save() each document separately:

    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() (awaited) returns single document so you cannot use .map():

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