node.js 和 mongodb 在现有数据库中按顺序递增 _id

问题描述

大家早上好。

所以我正在做一个类作业,其中我连接到现有的 mongoDB 数据库(通过 node.js 服务器),并且我从 HTML 站点上的表单向其中添加了一堆数据。我已经正确添加了表单信息,但是有两个字段服务器端没有响应新数据。有一个主键 (_id),它不是从当前的最后一个数字递增,而是由 ObjectId('longnumericvale') 递增,而 CustomerID 由未定义的值填充。数据库中存在的最后一条记录的 _id 和 CustomerId 为相同的数字。我怎样才能让 node.js 查看这个数字并在它添加我的表单数据作为 mongodb 数据库中的新文档时自动增加它。代码如下:

    app.post("/orderform",(req,res) => { //This takes post action from html and stores it
    console.log("successfully posted")
    var item = {
        CustFirstName: req.body.CustFirstName,CustLastName: req.body.CustLastName,CustAddress: req.body.CustAddress,CustCity: req.body.CustCity,CustProv: req.body.CustProv,CustPostal: req.body.CustPostal,CustCountry: req.body.CustCountry,CustHomePhone: req.body.CustHomePhone,CustBusPhone: req.body.CustBusPhone,Custemail: req.body.Custemail,userid: req.body.userid,passwd: req.body.passwd,};
    console.log("Customer information stored as:");//this is just a debug to the console to make sure it's grabbing the info
    console.log(item);
//here we connect to the datbase,and insert every item above to its corresponding position in the "customers" collection of "travelexperts" database
    mongo.connect(mongoUrl,{ useNewUrlParser: true,useUnifiedTopology: true },(err,client) => {
            if (err) throw err;
            //select database
            const db = client.db("travelexperts");
            //grab a collection
            const collection = db.collection("customers");

            collection.insertOne(item,res) => {
                if (err) throw err;
                console.log("Items inserted");
                db.close;
            });
        });//endconnection

    res.redirect('/thanks');
    console.log("finished,redirected")
});

//render thank you page for after submitting order
app.get('/thanks',res) =>{
    res.render("thanks");
});

我已经阅读了关于自动增量的 mongodb 文档,但是在我的具体示例中如何实现它有点超出我的范围。

更新

所以也许我没有很好地解释这个问题。我现在正在尝试登录两个单独的集合,并且可以正常工作。使用以下代码

app.post("/orderform",res) => { //This takes post action from Order.html form and stores all form inputs with corresponding names in a variable called item
    console.log("successfully posted")

    var item = {
        CustFirstName: req.body.CustFirstName,};

    console.log("This should be an array of all entered customer info:");//this is just a debug to the console to make sure it's grabbing the info
    console.log(item);

    var book = {
        BookingId: "",BookingDate: new Date(),BookingNo: "",TravelerCount:"",CustomerId: "",TripTypeId:"",PackageId: Number(req.query.packId),};

    console.log(book);
//here we connect to the datbase,and insert every item/booking above to its corresponding position in the "customers" collection of "travelexperts" database
    mongo.connect(mongoUrl,client) => {
            if (err) throw err;
            const db = client.db("travelexperts");
            const collection = db.collection("customers");
            const booking = db.collection("bookings");

            collection.insertOne(item,res) => {
                if (err) throw err;
                console.log("Items inserted");
            });

            
            booking.insertOne(book,res) => {
                if (err) throw err;
                console.log("Items inserted");
            });
            db.close;
        });//endconnection

    res.redirect('/thanks');
    console.log("finished,redirected")
});

所以问题是,对于收藏和预订,它们的记录都不完整。 collections 有 26 个文档,最后一个 _id 是 144。这就是为什么我需要读取 _id 并为每个新记录增加 +1。每个集合都有一个 _id 字段,然后是一个应与其匹配的 customerId 和 BookinbId。非常感谢到目前为止的所有帮助,但这些解决方案似乎都不起作用。我在 collections.insertone 行之前尝试了这两种方法,并尝试在控制台记录它们,它们只是在控制台中返回 [object Object] 而不是 _id 值。

解决方法

要为您的文档插入自定义 ID 字段,您应该将 _id 字段附加到您的 item 对象。

最简单的方法是创建一个全局 id_counter 变量,每次执行 /orderform API 时都会增加该变量。

let idCounter = 1;

.
.
.
const itemDoc = {_id: idCounter++,...item}
collection.insertOne(itemDoc,(err,res) => {
     if (err) throw err;
     console.log("Items inserted");
     db.close;
});

.
.
.


您还可以获取最后插入的 Item 的 id 并简单地增加它,这样可以节省大量精力来保持文档的 ids 同步,以防服务器重新启动或其他原因。

在这种情况下,您可以使用 collection.countDocuments() 方法执行以下操作:

let docLength = 0 // global variable
.
.
.
// inside your api endpoint controller...

collection.countDocuments({},{},res)=> {
   docLength = res;
})
const itemDoc = {_id: docLength++,res) => {
     if (err) throw err;
     console.log("Items inserted");
     db.close;
});