Mar*_*ane 37 javascript mongoose mongodb node.js
使用Mongoose将文档(记录)插入MongoDB有哪些不同的方法?
我目前的尝试:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var notificationsSchema = mongoose.Schema({
"datetime" : {
type: Date,
default: Date.now
},
"ownerId":{
type:String
},
"customerId" : {
type:String
},
"title" : {
type:String
},
"message" : {
type:String
}
});
var notifications = module.exports = mongoose.model('notifications', notificationsSchema);
module.exports.saveNotification = function(notificationObj, callback){
//notifications.insert(notificationObj); won't work
//notifications.save(notificationObj); won't work
notifications.create(notificationObj); //work but created duplicated document
}
Run Code Online (Sandbox Code Playgroud)
知道为什么插入和保存在我的情况下不起作用?我尝试创建,它插入2个文件而不是1.这很奇怪.
Ice*_*man 55
它.save()
是模型的实例方法,而.create()
直接从Model
作为方法调用调用,本质上是静态的,并将对象作为第一个参数.
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
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!
})
}
Run Code Online (Sandbox Code Playgroud)
导出您想要的任何功能.
更多关于Mongoose Docs,或者考虑阅读Model
Mongoose 中的原型参考.
小智 9
TLDR:使用“创建”(保存为专家模式)
在 Mongoose 中使用 create 和 save 方法的主要区别在于,create 是一种方便的方法,会自动为您调用 new Model() 和 save(),而 save 是在 Mongoose 文档实例上调用的方法。
当您在 Mongoose 模型上调用 create 方法时,它会创建模型的新实例,设置属性,然后将文档保存到数据库。当您想要创建一个新文档并将其一步插入数据库时,此方法非常有用。这使得创建成为原子事务。因此,save 方法可能会导致代码效率低下/不一致。
另一方面,在对 Mongoose 文档的实例进行更改后,将调用 save 方法。此方法将验证文档并将更改保存到数据库。
另一个区别是 create 方法可以通过传递文档数组作为参数来一次插入多个文档,而 save 旨在用于单个文档。
因此,如果您想创建一个模型的新实例并将其一步保存到数据库中,您可以使用 create 方法。如果您想要将模型的现有实例保存到数据库中,则应使用 save 方法。
此外,如果您的内容架构中有任何验证或预保存挂钩,则在使用 create 方法时将会触发该挂钩。
小智 7
您可以使用save()
或create()
。
save()
只能在模型的新文档上使用,而create()
可以在模型上使用。下面,我举了一个简单的例子。
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;
Run Code Online (Sandbox Code Playgroud)
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();
}
Run Code Online (Sandbox Code Playgroud)
确保使用方法 1 或方法 2。
归档时间: |
|
查看次数: |
54793 次 |
最近记录: |