I have this code:
var newresult = ""
oneDoc = { "adClientID": *randomID*, "adClientName": "abc", "adClientNameUPC": "ABC" }
newdoc.push(oneDoc)
await AdClient.create(newdoc, (err, result) => {
console.log(result)
console.log(result.adClientID)
newresult = result
})
console.log(newresult)
Now I need to access the values that have been added to the collection.
With this code, the line that prints "result" works fine and print the following:
{
adClientID: 'da7d3d78-b873-4cdd-ae85-3726d3cbd8a7',
adClientName: 'abc',
adClientNameUPC: 'ABC',
_id: '5f6e4582a790764cab84f586',
__v: 0
}
But the line that prints result.adClientID
returns undefined and the line that prints newresult
returns an empty string.
What am I missing that prevent me to access specific data that was added?
I could be wrong, but I think your await
is not actually awaiting anything. Mongoose says that this function can return a Promise (which can be awaited) or undefined.
Returns undefined if used with callback or a Promise otherwise.
I would recommend against mixing styles of asynchronous programming anyways.
I'm not too familiar with .create
specifically because we usually use upserts, but here is how I would write it:
const updated = await AdModel.findOneAndUpdate(
{ adClientID: oneDoc.adClientID },
{ $set: { ...oneDoc } },
{ new: true, upsert: true, ...options },
}).lean();
console.log(updated);
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.