Mongoose 是一个面向 MongoDB 的对象数据模型(ODM)库,它为在 Node.js 中使用 MongoDB 提供了便捷的 API。在Mongoose中,save
、insert
和create
函数都用于将数据保存到MongoDB数据库中,但它们各自的使用场景和工作方式略有不同。
save
方法
save
方法是Mongoose模型实例上的一个方法。它用于将一个模型实例(document)保存到数据库中。如果该模型实例是新创建的,则执行插入(insert)操作;如果该模型实例已经存在于数据库中(通常是通过查询得到的),则执行更新(update)操作。
示例:
javascriptconst kitty = new Cat({ name: 'Zildjian' }); kitty.save((err, savedKitty) => { if (err) return console.error(err); console.log(savedKitty.name + ' saved to database.'); });
insert
方法
insert
是MongoDB原生驱动的方法,Mongoose 通过 Model.collection.insert
或者 Model.insertMany
方法暴露了这一功能。这个方法通常用于批量插入多个文档到数据库中,不会进行模型的验证(validation),不会应用默认值,并且不会执行Mongoose的中间件(middleware)。
示例:
javascriptCat.insertMany([{ name: 'Kitty' }, { name: 'Catnip' }], (err, docs) => { if (err) return console.error(err); console.log('Multiple cats inserted to database.'); });
create
方法
create
方法是一个模型(model)上的静态方法,它不仅可以创建单个文档,也可以创建多个文档,并将它们保存到数据库中。与 insertMany
不同,create
方法会进行模型验证,应用模型的默认值,并且可以触发Mongoose的中间件。
示例:
javascriptCat.create({ name: 'Fluffy' }, (err, createdCat) => { if (err) return console.error(err); console.log(createdCat.name + ' created and saved to database.'); });
或者创建多个文档:
javascriptCat.create([{ name: 'Fluffy' }, { name: 'Paws' }], (err, createdCats) => { if (err) return console.error(err); createdCats.forEach(cat => console.log(cat.name + ' created and saved to database.')); });
总结
- save: 用于保存单个文档,可以是新文档(insert)也可以是更新已有文档(update),执行模型验证、应用默认值,并触发中间件。
- insert: 通过MongoDB驱动提供的能力,用于批量插入文档,不进行Mongoose层面的验证、不应用默认值,不触发中间件。
- create: 创建一个或多个文档并保存,执行模型验证、应用默认值,并触发中间件,适合需要验证和应用模型默认值的场景。
在实际应用中,选择哪一个方法取决于具体的场景和需求。例如,如果需要批量插入数据且不关心验证和默认值,可能会选择 insertMany
。如果在插入数据的同时需要验证和应用默认值,则可能会选择 create
。而 save
通常用于处理单个文档,并且在已有实例的基础上进行更新操作。