无法在noddejs中使用mongoDB和mongoose通过ID更新课程

问题描述 投票:0回答:1
const mongoose = require('mongoose');

mongoose.connect("mongodb://localhost:27017/mongo-exercise")
.then( ()=> console.log("Connected to MongoDB..."))
.catch(err => console.error("Failed to connect to db...",err));

以下是课程架构和模型

const courseSchema = new mongoose.Schema({
    name:String,
    author:String,
    tags:[String],
    date:Date,
    isPublished: Boolean,
    price:Number
});

const Course = mongoose.model('Course',courseSchema);

这是根据一定条件获取课程列表的功能。

async function getCourses() {
    return await Course
    .find({isPublished:true})
    .or([
        {price : {$gte: 15}},
        {name : /.*by.*/}
        ])
    .sort('-price')
    .select('name author price')
};

这里是通过 ID 更新特定课程的课程作者的功能,但未找到其失败和回复课程

async function updateCourse(id) {
    const mongoose = require('mongoose');
    console.log('checking..');
    if (!mongoose.Types.ObjectId.isValid(id)) {
    console.log('Invalid ID format');
    return;
}
    try {
        const course = await Course.findById(id);
        if (!course) {
            console.log('Course not found');
            return;
        }

        course.isPublished = false;
        course.author = 'Manish';

        const result = await course.save();
        console.log(result);
    } catch (error) {
        console.error('Error updating the course:', error);
    }
}

我正在尝试更新课程 ID 以及数据库中存在的类似其他 ID,但它不起作用。但是当查询数据库时,会出现相同的 id。

async function run() {
    const courses = await getCourses();
    console.log("List of courses \n" ,courses);
    
}
updateCourse('5a68fdd7bee8ea64649c2777');

这是查询数据库的输出

List of courses
 [
  {
    _id: new ObjectId('5a68fdd7bee8ea64649c2777'),
    name: 'Node.js Course',
    author: 'Mosh',
    price: 20
  },
  {
    _id: new ObjectId('5a6900fff467be65019a9001'),
    name: 'Angular Course',
    author: 'Mosh',
    price: 15
  },
  {
    _id: new ObjectId('5a68fde3f09ad7646ddec17e'),
    name: 'ASP.NET MVC Course',
    author: 'Mosh',
    price: 15
  },
  {
    _id: new ObjectId('5a68fe2142ae6a6482c4c9cb'),
    name: 'Node.js Course by Jack',
    author: 'Jack',
    price: 12
  }
]

这是更新输出

正在检查..

已连接到 MongoDB...

找不到课程

我尝试过此解决方案,通过名称及其工作方式找到课程。

async function testQuery() {
    const course = await Course.findOne({ name: 'React Course' });
    console.log('Course found by name:', course);
}

debugQuery();

它没有更新课程的潜在原因是什么,或者我的方法有问题吗?

node.js mongodb mongoose mongoose-schema
1个回答
0
投票

问题是你的模式没有

_id: String
,所以猫鼬无法识别它,默认情况下认为_id是一个ObjectId而不是字符串。

只需像这样更改您的架构,它应该可以工作

const courseSchema = new mongoose.Schema({
  _id: String,
  name: String,
  author: String,
  tags: [String],
  date: Date,
  isPublished: Boolean,
  price: Number
});
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.