我正在学习使用MongoDB和mongoose.js。我想插入一个文档并更新它。当我运行app.js时,它会记录“已成功更新”,但当我在mongo shell中预览它时,没有任何修改,即:“美丽的红色”保持不变。
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.");
}
});
3条答案
按热度按时间f2uvfpb91#
save()返回一个承诺,等待它执行。
https://mongoosejs.com/docs/promises.html
brc7rcf02#
我猜你需要像这样使用$set:
文档:https://mongoosejs.com/docs/documents.html#updating
对于您的案例:
31moq8wy3#
是的,这是等待从www.example.com()返回的承诺的问题document.save;在mongoDB中,每次您处理数据库时,如create、findOne、updateOne、delete等,这些都返回承诺,您将不得不等待它们。