[英]Node.js + MongoDB: insert one and return the newly inserted document
我想知道是否有辦法插入新文檔並將其返回到一個 go 中。
這是我目前正在使用的:
db.collection('mycollection').insertOne(options, function (error, response) {
...
});
response
結果包含有關命令是否成功以及插入的記錄數的信息。
如果要返回插入的數據,可以嘗試response.ops
,例如:
db.collection('mycollection').insertOne(doc, function (error, response) {
if(error) {
console.log('Error occurred while inserting');
// return
} else {
console.log('inserted record', response.ops[0]);
// return
}
});
insertOne
官方文檔:
http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#insertOne
callback
類型:
http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpCallback
result
類型:
http://mongodb.github.io/node-mongodb-native/3.1/api/Collection.html#~insertOneWriteOpResult
以下代碼對我有用,在MongoDB 版本 2.2.33 中。
db.collection("sample_collection").insertOne({
field1: "abcde"
}, (err, result) => {
if(err) console.log(err);
else console.log(result.ops[0].field1)
}
發布此信息,因為這可能對某人有所幫助。 您可以像這樣找到更新的對象:
await req.db
.collection('users')
.insertOne({ email, password: hashedPassword, name })
.then(({ ops }) => ops[0]);
對於那些使用MongoDB 驅動程序 4.x 的人,我找到了一個使用findOneAndUpdate的解決方法:
const toInsert = {
_id: mongo.ObjectId(),
someField: 'hello',
someOtherField: 'world'
};
const options = { upsert: true, returnDocument: 'after' };
const { value: document } = await db.collection.findOneAndUpdate(
toInsert,
{ $set: {} },
options
);
注意toInsert
中的_id
是一個新生成的ObjectId
。
更新是空的( { $set: {} }
)並且什么都不做,因為我們不需要更新,我們只想更新我們的文檔。 它仍然需要,因為更新不能為null
或空對象。
由於returnDocument
選項,新創建的文檔將作為結果中的值返回。
為了避免空更新,另一種解決方案是使用$setOnInsert
:
const toInsert = { someField: 'hello', someOtherField: 'world' };
const options = { upsert: true, returnDocument: 'after' };
const { value: document } = await db.collection.findOneAndUpdate(
{ _id: mongo.ObjectId() },
{ $setOnInsert: toInsert },
options
);
你可以使用mongojs來做到這一點。
db.collection('mycollection').save(doc, function(error, response){
// response has _id
})
試試這個
try {
let collection = db.collection('collection_name'); let { ops: inserted } =
await collection.insertOne({ data: object });
// can access array of inserted record like :
console.log(inserted)
} catch (error) {
// log errors
}
我想仍然使用 .then() 通過插入來解決,所以我最終將所有內容都包裝在它自己的承諾中。
return new Promise((resolve, reject) => {
db.collection('entries').insertOne({ entry }, (err, res) => {
if (err) {
console.log('error', err);
reject(null);
} else {
resolve(res.ops[0]);
}
});
});
那我就可以做
insertEntry({}).then(entry=>{})
正如勞倫在官方 mongodb 論壇中所說,這是預期的行為。 我在這里復制她的回復:
我們的驅動程序符合 MongoDB CRUD 規范,這是驅動程序 v4 中的新功能
當你
insertOne
你現在得到insertedId
,所以它應該提供由數據庫處理的文檔的唯一“新”部分。
const myDoc = { a: 1 }
myDoc._id = (await c.insertOne(myDoc)).insertedId
// myDoc is now the same as the doc inserted into mongodb
您可以返回使用 id 插入的文檔
async insertProduct(product) {
const record = await db.collection("products").insertOne(product);
return {id: record.insertedId, ...product }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.