[英]How do I get the ID of the document I just inserted into MongoDB? (API)
[英]How to get MongoDB _id of an inserted document
我想在我的 MongoDB 數據庫中創建一個文檔並獲取新文檔的 _id。 這就是我正在做的事情:
const mongoose = require("mongoose");
const billingSchema = require("./models/billing");
const { ObjectId } = require("bson");
const { MongoClient } = require("mongodb");
const mongouri = "***";
var connection = mongoose.createConnection(mongouri);
var Bills = connection.model("Fatturazione", billingSchema, "Fatturazione");
exports.createBill = (b) => {
return new Promise((resolve, reject) => {
Bills.Create(b, function (err) {
if (err) {
reject(err);
} else {
console.log(mongoose.Types.ObjectId(b._id));
resolve();
}
});
});
};
這是我的架構:
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
//schema define the structure of the document
const billingSchema = new Schema({
data_fatturazione: {
type: Date,
required: true,
},
data_saldo: {
type: Date,
required: false,
},
totale: {
type: Number,
required: false,
},
pagato: {
type: Boolean,
required: false,
},
});
module.exports = billingSchema;
在console.log()
我想打印最后插入的文檔的 _id,但它打印一個不存在的 id(它不對應於數據庫中最后創建的文檔的 _id)。 我也嘗試不使用mongoose.Types.ObjectId()
但它打印undefined
。 我不明白問題出在哪里。
我在另一個 js 文件中調用 function createBill()
,並傳遞了一個帶有正確字段的 object。
您正在嘗試獲取參數b
的_id
,該參數傳遞給您的createBill
,這在邏輯上是未定義的。 相反,您必須從Bill.create
的結果中獲取 _id , mongoose 回調需要 2 個 arguments 作為評論中提到的@Joe,因此您的代碼必須如下所示:
exports.createBill = (b) => { return new Promise((resolve, reject) => { Bills.Create(b, function (err, result) { if (err) { reject(err); } else { console.log(result._id); resolve(result); } }); }); };
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.