Below code snippet is working fine.
function simple() {
return 10000;
}
db.Invoice.create({
items: selectedItems,
_id: simple("userid")
});
But if I change simple function
to this
async function getNextSequence(sequenceName) {
const sequenceDocument = await db.Counter.findOneAndUpdate(
{ _id: sequenceName },
{ $inc: { seq: 1 } },
{ new: true }
);
console.log("seq", sequenceDocument);
return sequenceDocument.seq;
}
db.Invoice.create({
items: selectedItems,
_id: getNextSequence("userid")
});
This gives me an error.
ValidationError: Invoice validation failed: _id: Cast to Number failed for value "Promise { }" at path "_id"
Why could this happen?
getNextSequence
is an asynchronous function which needs to be awaited - otherwise you're trying to save Promise
to your MongoDB which is not supported. Try:
db.Invoice.create({
items: selectedItems,
_id: await getNextSequence('userid'),
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.