我正在學習 MongoDB 和 Mongoose,我看過講師建議使用 save() 函式來保存對資料庫所做的更改。
但是我仍然在不使用 save() 的情況下成功地進行了更改。我創建了兩個函式來向資料庫添加檔案,一個使用 save(),第二個不使用 save(),它們都完成了相同的作業。
那么,使用它有什么意義呢?
注意:我隱藏了我的連接字串
我的代碼:
const express = require('express');
const mongoose = require('mongoose');
//-- Connect to Database --//:
mongoose.connect();
// make Schema & model:
const Person = mongoose.model('Person', new mongoose.Schema({
name: String,
age: Number
}));
//-- Interact with Database --//:
async function run1 () {
const person = await Person.create({name: 'John', age: 25});
await person.save();
console.log(person);
}
async function run2 () {
const person = await Person.create({name: 'Sally', age: 40});
console.log(person);
}
run1();
run2();
終端輸出:
PS C:\Users\user\OneDrive\Desktop\Folders\Programming\Web Development\Web Development Projects\Database-Practice> node server
{
name: 'Sally',
age: 40,
_id: new ObjectId("61d20d852b1e59a6b21149b1"), __v: 0
}
{
name: 'John',
age: 25,
_id: new ObjectId("61d20d852b1e59a6b21149b0"), __v: 0
}
運行我的代碼后我的資料庫的圖片:

uj5u.com熱心網友回復:
Mongoose 模型有一個常用于創建新檔案的 create() 函式。
const User = mongoose.model('User', mongoose.Schema({
email: String
}));
const doc = await User.create({ email: '[email protected]' });
doc.email; // '[email protected]'
create() 函式是一個圍繞 save() 函式的瘦包裝器。上面的 create() 呼叫等效于:
const doc = new User({ email: '[email protected]' });
await doc.save();
使用 create() 的最常見原因是您可以通過傳遞物件陣列,使用單個函式呼叫方便地 save() 多個檔案:
const User = mongoose.model('User', mongoose.Schema({
email: String
}));
const docs = await User.create([
{ email: '[email protected]' },
{ email: '[email protected]' }
]);
docs[0] instanceof User; // true
docs[0].email; // '[email protected]'
docs[1].email; // '[email protected]'
uj5u.com熱心網友回復:
從檔案:
將一個或多個檔案保存到資料庫的快捷方式。為 docs
MyModel.create(docs)中new MyModel(doc).save()的每個 doc 做。
看看你所擁有的,讓我指出:
async function run1 () {
const person = await Person.create({name: 'John', age: 25});
await person.save(); // unnecessary 2nd call here
console.log(person);
}
在幕后,您的代碼將運行如下:
async function run1 () {
const person = await new Person({name: 'John', age: 25}).save();
await person.save(); // saving twice basically
console.log(person);
}
您可以做的是(這是大多數人的首選):
async function run1 () {
const person = new Person({name: 'John', age: 25});
await person.save();
}
原因是這樣做可以讓您在保存檔案時有更多控制權。例如,您可以將 person 物件傳遞給任何函式并將其保存在該函式中,而不需要將模型放到代碼庫中該函式存在的任何位置。
async function run1 () {
const person = new Person({name: 'John', age: 25});
await doSth(person); // showing possibility, not a recommendation
}
// This function can exist anywhere, does not have to be in the same file
async doSth(person){
// do some logging maybe
// change some properties of the person maybe
// slug-ify the persons name maybe
await person.save();
}
這樣做可以讓您更好地分離關注點。除此之外,兩者都會產生相同的行為,并且幾乎是偏好問題。但是目前社區的標準是采用這種.save()方法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/402941.html
標籤:
下一篇:帶有物件陣列的貓鼬條件更新
