更新文档时,.save不是函数,.map不是函数

时间:2020-01-01 21:39:15

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

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

“消息”:“ 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不是函数”

帐户总是返回值,然后为什么我无法理解它为什么不能映射。

感谢您的帮助。谢谢

1 个答案:

答案 0 :(得分: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();
相关问题