Mongoose Model.update在我的代码中不起作用

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

我想用给定的id更新一些课程属性。这是我的代码:

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

const Course = mongoose.model('Course', courseSchema);
mongoose.connect('mongodb://localhost/mongo-exercises');

async function updateCourse(id) {
     const result = await Course.update({_id: id}, {
        $set: {
            author: 'New', 
            isPublished: false
        }
    });

console.log(result);
}

updateCourse('5a68fde3f09ad7646ddec17e');

在控制台上我得到{ok: 1, nModified: 0, n: 0}

我试过用另一种方式更新元素,但它不起作用。对于这段代码,我没有得到结果,没有回应:

const course = await Course.findById(id);
  if(!course) return; 

  course.isPublished = true; 
  course.author = 'Another Author';

  const result = await course.save();
  console.log(result);

当我尝试使用findByIdAndUpdate与其他代码进行更新时,结果在控制台中为null:

 async function updateCourse(id) {
    const course = await Course.findByIdAndUpdate(id, {
    $set: {
        author: 'Billy',
        isPublished: false
    }
 });

   console.log(course);

 }
updateCourse('5a68fde3f09ad7646ddec17e');

我正在使用的数据库有:

 { _id: 5a68fdd7bee8ea64649c2777,
   name: 'Node.js Course',
   author: 'Sam',
   isPublished: true,
   price: 20 },
 { _id: 5a68fde3f09ad7646ddec17e,
   name: 'ASP.NET MVC Course',
   author: 'Mosh',
   isPublished: true,
   price: 15 },
 { _id: 5a6900fff467be65019a9001,
   name: 'Angular Course',
   author: 'Mosh',
   isPublished: true,
   price: 15 },
 { _id: 5a68fe2142ae6a6482c4c9cb,
   name: 'Node.js Course by Jack',
   author: 'Jack',
   isPublished: true,
   price: 12 }

课程不会更新。错误在哪里?请注意,如果我想创建新文档,它没有问题。

node.js database mongodb mongoose backend
5个回答
0
投票

update({_ id:id},...)指定_id期望文档中的_id类型为ObjectID。

update()和findById(),找不到_id,并返回null,因为_id类型可能是你的集合/文档中的String, - 用Compass检查。


0
投票

根据MongoDB update doc,我在代码中没有看到任何问题,这里查询和语法是正确的。

update()方法返回包含操作状态的WriteResult对象。成功后,WriteResult对象包含与查询条件匹配的文档数,更新插入的文档数以及修改的文档数。

此处没有修改任何文档,唯一的原因是,您要在查询中设置相同的数据进行更新。


0
投票

尝试使用

isPublished: {
    type: Boolean,
    default: false
}

代替

isPublished: Boolean

0
投票

返回{ok: 1, nModified: 0, n: 0}说操作成功但找不到,也没有更新任何条目,这意味着它甚至不匹配。

我不完全确定,但我认为猫鼬只能通过ObjectId而不是string找到ID。

所以你应该通过转换得到所需的结果,如下:

const result = await Course.update({ _id: mongoose.Types.ObjectId(id) }, { 
    $set: { author: 'New', isPublished: false }
});

0
投票

在架构中添加_id:String

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

用这个取代你的承诺:

async function updateCourse(id) {
  const result = await Course.update({ _id: mongoose.Types.ObjectId(id) }, { 
    $set: { author: 'New Author', isPublished: false }
  });

我在mosh node.js课程中遇到了同样的问题,这个解决方案对我有用! :)

© www.soinside.com 2019 - 2024. All rights reserved.