首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在Document.save() - mongoose.js之前执行Model.updateOne()

在Document.save() - mongoose.js之前执行Model.updateOne()
EN

Stack Overflow用户
提问于 2020-05-14 00:51:15
回答 2查看 500关注 0票数 1

我正在尝试学习在mongoose.js中使用MongoDB。我想插入一个文档并更新它。当我运行app.js时,它记录“成功更新”,但当我在mongo shell中预览它时,没有任何修改,即查看:"Pretty Red“。保持不变。

代码语言:javascript
复制
 const mongoose = require('mongoose');

// Connection URL
const url = 'mongodb://localhost:27017/fruitsDB'; //creates fruitsDB

// Connect to database server
mongoose.connect(url, {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// Define a schema/table structure
const fruitSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, "No name specified. Try Again!"] //validation with error message
  },
  rating: {
    type: Number,
    min: 1, //validation
    max: 10 //validation
  },
  review: String
});

// Create a model from the structure
const Fruit = mongoose.model("Fruit", fruitSchema);

// Create a document that follows a model
const fruit = new Fruit({
  name: "Apple",
  rating: 6,
  review: "Pretty Red."
});

// Save the new document/entry
fruit.save();

// Update single document
Fruit.updateOne({name: "Apple"}, {review: "Review Changed!"}, function(err) {
  if(err) {
    console.log(err);
  } else {
    console.log("Successfully updated.");
  }
});
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2020-05-14 09:53:46

.save()返回一个promise,等待它执行。

https://mongoosejs.com/docs/promises.html

票数 0
EN

Stack Overflow用户

发布于 2020-05-14 01:06:28

我想你需要像这样使用$set:

代码语言:javascript
复制
// Mongoose sends a `updateOne({ _id: doc._id }, { $set: { name: 'foo' } })`

文档:https://mongoosejs.com/docs/documents.html#updating

对于您的案例:

代码语言:javascript
复制
Fruit.updateOne({name: "Apple"}, { $set : {review: "Review Changed!"}}, function(err) {
  if(err) {
    console.log(err);
  } else {
    console.log("Successfully updated.");
  }
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/61780341

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档