nodejs/mongoose。最好使用哪种方法来创建文档?
题
当我与Mongoose合作时,我发现了两种在Nodejs中创建新文档的方法。
第一的:
var instance = new MyModel();
instance.key = 'hello';
instance.save(function (err) {
//
});
第二
MyModel.create({key: 'hello'}, function (err) {
//
});
有区别吗?
解决方案
是的,主要区别是在保存之前进行计算或作为对建立新模型时出现的信息的反应。最常见的示例是在尝试保存之前确保模型有效。其他一些示例可能是在保存之前创建任何缺失的关系,需要根据其他属性进行即时计算的值,以及需要存在但可能永远不会保存到数据库(中止交易)的模型。
因此,作为您可以做的一些事情的基本示例:
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) {
//
});
其他提示
此代码是为了将文档数组保存到数据库中:
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)'允许创建具有模型名称的集合并执行 .save()
仅将文档用于数组的方法。
另外,您可以以这种方式保存一个文档:
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)
});
我更喜欢一个简单的示例,其中有预定义的用户值和验证检查模型侧。
// 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.
});
不隶属于 StackOverflow