2012-02-16 26 views
36

我發現了兩種方法,當我使用貓鼬工作時,在nodejs中創建新文檔。Nodejs/mongoose。哪種方法比創建文檔更可取?

首先

var instance = new MyModel(); 
instance.key = 'hello'; 
instance.save(function (err) { 
    // 
}); 

MyModel.create({key: 'hello'}, function (err) { 
    // 
}); 

有什麼區別?

回答

36

是的,主要區別在於您可以在保存之前進行計算,或者在您構建新模型時出現的信息反應。最常見的例子是在試圖保存模型之前確保模型是有效的。其他一些示例可能會在保存之前創建任何缺失的關係,需要基於其他屬性動態計算的值以及需要存在但可能永遠不會保存到數據庫的模型(異常事務)。

所以爲一些事情一個基本的例子,你可以這樣做:

var instance = new MyModel(); 

// Validating 
assert(!instance.errors.length); 

// Attributes dependent on other fields 
instance.foo = (instance.bar) ? 'bar' : 'foo'; 

// Create missing associations 
AuthorModel.find({ name: 'Johnny McAwesome' }, function (err, docs) { 
    if (!docs.length) { 
    // ... Create the missing object 
    } 
}); 

// Ditch the model on abort without hitting the database. 
if(abort) { 
    delete instance; 
} 

instance.save(function (err) { 
    // 
}); 
+4

謝謝,很好的解釋:) – 2012-12-14 19:04:36

+0

除了這種方式,你需要自己生成的ID。 mongoose.Types.ObjectId()是_id的格式。 – 2016-06-29 19:15:53

+0

異步和同步怎麼樣,都是同步操作? – JohnnyQ 2017-03-09 14:50:39

0

我喜歡用預先定義的用戶價值和驗證檢查模型邊一個簡單的例子。

// Create new user. 
    let newUser = { 
     username: req.body.username, 
     password: passwordHashed, 
     salt: salt, 
     authorisationKey: authCode 
    }; 

    // From require('UserModel'); 
    return ModelUser.create(newUser); 

,那麼你應該使用的模型類驗證(因爲這可以在其他位置使用,這將有助於減少錯誤/加快發展)

// Save user but perform checks first. 
gameScheme.post('pre', function(userObj, next) { 
    // Do some validation. 
}); 
3

此代碼是在保存陣列的文檔轉換成數據庫:

app.get("/api/setupTodos", function (req, res) { 

var nameModel = mongoose.model("nameModel", yourSchema); 
//create an array of documents 
var listDocuments= [ 
    { 
     username: "test", 
     todo: "Buy milk", 
     isDone: true, 
     hasAttachment: false 
    }, 
    { 
     username: "test", 
     todo: "Feed dog", 
     isDone: false, 
     hasAttachment: false 
    }, 
    { 
     username: "test", 
     todo: "Learn Node", 
     isDone: false, 
     hasAttachment: false 
    } 
]; 

nameModel.create(listDocuments, function (err, results) { 

    res.send(results); 
}); 

「nameModel.create(listDocuments)」許可證,創造一個集與模型的名稱和執行只有文件進入數組的10種方法。

或者,你可以用這種方式保存一個唯一文件:

var myModule= mongoose.model("nameModel", yourSchema); 

    var firstDocument = myModule({ 
     name: String, 
surname: String 
    }); 

firstDocument.save(function(err, result) { 
    if(if err) throw err; 
    res.send(result) 

});

相關問題