-1

I'm trying to query a specific document and then delete that document.

I'm able to successfully query the document through this:

export async function findRecord(database, sub_db, query) {
    let output = "";
    const mongo = require('mongodb').MongoClient
    const url = "mongodb+srv://...";
    const client = await mongo.connect(url, {useNewUrlParser: true,useUnifiedTopology: true});

    const db = client.db(database)
    const collection = db.collection(sub_db)
    const items = await collection.find(query).toArray();
    client.close()
    return items;
}

But when I console.log the data my _id is in an array. It looks like this: https://share.getcloudapp.com/rRun6j5J

Within the MongoDB docs I see to query like this: {"_id" : ObjectId("568c28fffc4be30d44d0398e")}, but because its printing an array I can't get it to look like that.

Frontend:

export async function button3_click(event) {
    let query = {}
    let output = await findRecord("domains","domains", query)
    console.log(output)
    let record_to_delete = output[0]._id
    console.log(record_to_delete)
    await deleteRecord("domains","domains",record_to_delete)
}

Backend:

export async function deleteRecord(database, sub_db, record_idobj) {
    let output = "";
    const mongo = require('mongodb').MongoClient
    const url = "mongodb+srv://...";
    const client = await mongo.connect(url, {useNewUrlParser: true,useUnifiedTopology: true});

    const db = client.db(database)
    const collection = db.collection(sub_db)
    await collection.deleteOne({"_id": record_idobj})
    client.close()
}

My end goal is to be able remove by _id...

Note: My frontend code might look weird because I'm in Wix Code, but everything else should be okay.

2 Answers2

0

Please try to use use findOne instead of find.

collection.findOne({_id: _id})

rjmacarthy
  • 2,164
  • 1
  • 13
  • 22
0

As long as I understand, the answer to your question is given here.

You just need to make a String from your char array, which can be done easily with charArray.join(""); and then you create an ObjectId with ObjectId(string)

ELKozel
  • 94
  • 3