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

问题描述 投票:1回答:2

我想用mongoose.js学习使用MongoDB,我想插入一个文档并更新它。当我运行app.js时,它记录了 "Successfully updated",但当我在mongo shell即review中预览它时,没有任何修改。"Pretty Red. "依然没有变化。

 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.");
  }
});
javascript node.js mongodb mongoose nosql
2个回答
0
投票

.save()返回一个承诺, await就可以了。

https:/mongoosejs.comdocspromises.html


0
投票

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

// Mongoose sends a `updateOne({ _id: doc._id }, { $set: { name: 'foo' } })`

Doc: https:/mongoosejs.comdocsdocuments.html#updating

对于你的情况。

Fruit.updateOne({name: "Apple"}, { $set : {review: "Review Changed!"}}, function(err) {
  if(err) {
    console.log(err);
  } else {
    console.log("Successfully updated.");
  }
});
© www.soinside.com 2019 - 2024. All rights reserved.