javascript - .create 和 .save 之间的 Mongoose 区别

标签 javascript node.js mongodb express mongoose

我在 udemy 上做了一个关于 Express 和 Mongoose 的训练营,假设我们想在数据中添加新字段,我们做了这样的事情

var playground = require("../models/playground.js");

route.post("/", middleware.isLoggedIn,function (req, res) {

  var name =  req.body.name;
  var image =  req.body.image;
  var description = req.body.description;
  var price = req.body.price;

  playground.create({
    name: name,
    image:image,
    description: description,
    price: price
  }, function(error, newlyCreated){
    if(error) {
      console.log(error)
    }
    else {
      newlyCreated.author.id = req.user._id;
      newlyCreated.author.username = req.user.username;
      newlyCreated.save();
     res.redirect("/playground");
    }
  })
});

现在,已经过去一年多了,我无法理解我在这里做什么(应该添加一些评论)但我确实看到我们正在使用类似这样的东西 playground.create({

还有这个我完全无法理解

          newlyCreated.author.id = req.user._id;
          newlyCreated.author.username = req.user.username;
          newlyCreated.save();

这不是主要问题,但是 newlyCreated.save(); 会做什么?我的意思是它可能会保存我们从前端获取的数据,但它如何工作?

继续讨论第一个问题,我再次遵循了一个教程,在该教程中,讲师做了一些像这样简单的事情来保存数据

 let author = new Author({  
     name: args.name, 
     age: args.age
       })
 author.save()

那么 .create.save 之间的一般区别是什么?

最佳答案

Model.create() is a shortcut for saving one or more documents to the database.

MyModel.create(docs) does new MyModel(doc).save() for every doc in docs.

This function triggers the following middleware.

  • save()

引用:https://mongoosejs.com/docs/api.html#model_Model.create

关于javascript - .create 和 .save 之间的 Mongoose 区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52872335/

相关文章:

javascript - 对字符串的 promise - [object Object] 或 [object Promise]?

mongodb - 在 Mongodb 中获取多个值的不同值

java - 具有多个可选参数的 Spring Data MongoDB AND/OR 查询

用于为 youtube 视频禁用鼠标单击的 Javascript 代码

javascript - 我如何检查 '.classname' 项目有多少?

javascript - 如何为可调整大小的 jQuery UI 元素启动调整大小功能(触发句柄拖动)

javascript - 关于Web应用程序如何工作以及服务器客户端如何实现的问题

node.js - 通过多种条件获取资源的最佳实践是什么?

MySQL 5.6.41 错误号 1064 : Creating a MySQL query with variables

javascript - 比较两个对象数组并根据 Javascript 中的 id 更新lastSeen