我正在尝试学习在mongoose.js中使用MongoDB。我想插入一个文档并更新它。当我运行app.js时,它记录“成功更新”,但当我在mongo shell中预览它时,没有任何修改,即查看:"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.");
}
});发布于 2020-05-14 09:53:46
.save()返回一个promise,等待它执行。
发布于 2020-05-14 01:06:28
我想你需要像这样使用$set:
// Mongoose sends a `updateOne({ _id: doc._id }, { $set: { name: 'foo' } })`文档:https://mongoosejs.com/docs/documents.html#updating
对于您的案例:
Fruit.updateOne({name: "Apple"}, { $set : {review: "Review Changed!"}}, function(err) {
if(err) {
console.log(err);
} else {
console.log("Successfully updated.");
}
});https://stackoverflow.com/questions/61780341
复制相似问题