乐闻世界logo
搜索文章和话题

Mongoose 中 save, insert 以及 create 三者之间的区别?

5 个月前提问
3 个月前修改
浏览次数32

5个答案

1
2
3
4
5

Mongoose 是一个面向 MongoDB 的对象数据模型(ODM)库,它为在 Node.js 中使用 MongoDB 提供了便捷的 API。在Mongoose中,saveinsertcreate函数都用于将数据保存到MongoDB数据库中,但它们各自的使用场景和工作方式略有不同。

save 方法

save 方法是Mongoose模型实例上的一个方法。它用于将一个模型实例(document)保存到数据库中。如果该模型实例是新创建的,则执行插入(insert)操作;如果该模型实例已经存在于数据库中(通常是通过查询得到的),则执行更新(update)操作。

示例:

javascript
const 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)。

示例:

javascript
Cat.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的中间件。

示例:

javascript
Cat.create({ name: 'Fluffy' }, (err, createdCat) => { if (err) return console.error(err); console.log(createdCat.name + ' created and saved to database.'); });

或者创建多个文档:

javascript
Cat.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 通常用于处理单个文档,并且在已有实例的基础上进行更新操作。

2024年6月29日 12:07 回复

The .save() is an instance method of the model, while the .create() is called directly from the Model as a method call, being static in nature, and takes the object as a first parameter.

shell
var mongoose = require('mongoose'); var notificationSchema = mongoose.Schema({ "datetime" : { type: Date, default: Date.now }, "ownerId":{ type:String }, "customerId" : { type:String }, "title" : { type:String }, "message" : { type:String } }); var Notification = mongoose.model('Notification', notificationsSchema); function saveNotification1(data) { var notification = new Notification(data); notification.save(function (err) { if (err) return handleError(err); // saved! }) } function saveNotification2(data) { Notification.create(data, function (err, small) { if (err) return handleError(err); // saved! }) }

Export whatever functions you would want outside.

More at the Mongoose Docs, or consider reading the reference of the Model prototype in Mongoose.

2024年6月29日 12:07 回复

TLDR: Use Create (save is expert-mode)

The main difference between using the create and save methods in Mongoose is that create is a convenience method that automatically calls new Model() and save() for you, while save is a method that is called on a Mongoose document instance.

When you call the create method on a Mongoose model, it creates a new instance of the model, sets the properties, and then saves the document to the database. This method is useful when you want to create a new document and insert it into the database in one step. This makes the creation an atomic transaction. Therefore, the save method leaves the potential to create inefficiencies/inconsistencies in your code.

On the other hand, the save method is called on an instance of a Mongoose document, after you have made changes to it. This method will validate the document and save the changes to the database.

Another difference is that create method can insert multiple documents at once, by passing an array of documents as parameter, while save is intended to be used on a single document.

So, if you want to create a new instance of a model and save it to the database in one step, you can use the create method. If you have an existing instance of a model that you want to save to the database, you should use the save method.

Also, if you have any validation or pre-save hook in your content schema, this will be triggered when using the create method.

2024年6月29日 12:07 回复

You can either use save() or create().

save() can only be used on a new document of the model while create() can be used on the model. Below, I have given a simple example.

Tour Model

shell
const mongoose = require("mongoose"); const tourSchema = new mongoose.Schema({ name: { type: String, required: [true, "A tour must have a name"], unique: true, }, rating: { type: Number, default:3.0, }, price: { type: Number, required: [true, "A tour must have a price"], }, }); const Tour = mongoose.model("Tour", tourSchema); module.exports = Tour;

Tour Controller

shell
const Tour = require('../models/tourModel'); exports.createTour = async (req, res) => { // method 1 const newTour = await Tour.create(req.body); // method 2 const newTour = new Tour(req.body); await newTour.save(); }

Make sure to use either Method 1 or Method 2.

2024年6月29日 12:07 回复

I'm quoting Mongoose's Constructing Documents documentation:

shell
const Tank = mongoose.model('Tank', yourSchema); const small = new Tank({ size: 'small' }); small.save(function (err) { if (err) return handleError(err); // saved! }); // or Tank.create({ size: 'small' }, function (err, small) { if (err) return handleError(err); // saved! }); // or, for inserting large batches of documents Tank.insertMany([{ size: 'small' }], function(err) { });
2024年6月29日 12:07 回复

你的答案