【问题标题】:Find and delete last entered entry from MongoDB collection从 MongoDB 集合中查找并删除最后输入的条目
【发布时间】:2020-12-03 00:17:56
【问题描述】:

我添加了一个元素,我需要从我的 mongodb 集合中删除它。这是我输入的最后一个条目。我一直在关注这个链接:How to delete the last item of a collection in mongodb。但是,我找不到 ID,也无法从光标 (?) 中提取此值。这是我到目前为止所做的:

const db = client.db(databaseName);

let x = db
.collection("ford_twitter")
.find()
.sort({_id:-1});

终端日志是:

【问题讨论】:

    标签: node.js mongodb mongodb-query


    【解决方案1】:

    如果它是最后一个条目,首先使用find 检查它是否存在。找到后,您可以将其删除。

    我会给你一个完整的例子来说明如何实现它:

    async function find(){
    try{
    const call = await MongoClient.connect(uri, {
      useNewUrlParser: true,
      useUnifiedTopology: true
    })
    result = await call.db("todos")
                       .collection("quotes")
                       .find({})
                       .sort("_id", -1).limit(1)
                       .toArray()
    console.log(result)                   
    } catch(e){console.log(e)}
    }
    find()
    

    在 MongoDB 中,有几个新对象,例如 Cursor。要获得标准对象,您需要阅读如何使用光标:它具有属性和方法...

    toArray() 将给出一个包含该元素的数组,您可以对其进行检查。

    【讨论】:

    • 这给了我以下错误:错误:非法排序子句,必须是 [['field1', '(ascending|descending)'], ['field2', '(ascending|降序)']]
    • 给我以下信息:ReferenceError: _id is not defined
    • 给我:承诺{ }
    • @cyruslk 这就是帖子应该包含的内容。试试看告诉我
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-12-26
    • 2019-10-25
    • 1970-01-01
    • 2014-05-15
    • 2018-11-23
    • 2011-05-17
    相关资源
    最近更新 更多