我想使用 mongoose 中的 updateOne 来更新我的数据

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

我的程序遇到一些问题。

我在mongodb中创建一个数据库用于练习,并使用mongoose插入一些数据, 现在我想使用 .updateOne() 函数更新一些数据,但它对我不起作用,即使我没有收到任何错误消息或其他内容。

我正在使用 MongoDB v6.0.1 猫鼬v7.0.1 节点v18.12.1

即使我尝试使用 MongoDB shell,但它们也不起作用,我不知道现在该怎么办。

这是我的app.js代码

const mongoose = require("mongoose");

mongoose.connect('mongodb://127.0.0.1:27017/fruitsDB');

// First Data Collection
const fruitSchema = new mongoose.Schema({
    name : {
        type : String,
        required : [true, "Please check your data entry, no name specified"]
    },
    rating : {
        type : Number,
        min : 1,
        max : 10
    },
    review : String
});

const Fruit = mongoose.model("Fruit", fruitSchema);

const fruit = new Fruit({
    // Validation require
    name : "Pineapple",
    rating : 5,
    review : "This is the best fruit"
});

// fruit.save();

Fruit.updateOne({_id:"6413227328c4dbee8166933c"},{review:"This is the best fruits"})

这是我的数据收集

> use fruitsDB
switched to db fruitsDB
> db.fruits.find()
{ "_id" : ObjectId("6413222a13b4de0491c61b7d"), "name" : "Pineapple", "rating" : 5, "review" : "This is the best fruit", "__v" : 0 }
{ "_id" : ObjectId("6413227328c4dbee8166933b"), "name" : "Kiwi", "rating" : 8, "review" : "Good", "__v" : 0 }
{ "_id" : ObjectId("6413227328c4dbee8166933d"), "name" : "Banana", "rating" : 8, "review" : "Good", "__v" : 0 }
{ "_id" : ObjectId("6413227328c4dbee8166933c"), "name" : "Orange", "rating" : 8, "review" : "Good", "__v" : 0 }
> 

当我尝试使用 .find() 打印所有数据时,此方法也不适合我,所以后来我使用 .then() 方法,现在它可以工作了。

Fruit.find().then(function(list){
    list.forEach((ele) => {
        console.log(ele.name)
    });
    mongoose.connection.close();
})

但是 .updateOne() 仍然不起作用,我尝试了很多方法,或者我犯了一些错误。 请帮助我了解我犯了什么错误以及在哪里。 谢谢!!

我想使用 mongoose 更新

我的数据
mongodb mongoose mongoose-schema
1个回答
0
投票

看看这是否适合您: 例如:将 kiwi 评级更新为 9

Fruit.updateOne({_id: "64e656a63afff4b4935da8a7"}, {$set: {rating: 
9}}).exec().then(() => {
    console.log("Fruit updated succesfully");
}).catch((err) => {
  console.error("Error updating fruit: ", err);
});
© www.soinside.com 2019 - 2024. All rights reserved.