【问题标题】:Mongoose Model.update not working in my codeMongoose Model.update 在我的代码中不起作用
【发布时间】:2019-02-13 21:23:54
【问题描述】:

我想用给定的 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 }

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

【问题讨论】:

  • authorisPublished 是否已经与您尝试设置的值相同?
  • 嗨。 isPublished 具有相同的值,但作者不同。我尝试过使用其他更新选项,例如通过其 id 查找元素然后更新它,但它不起作用。
  • 您正在尝试使用相同的硬编码值进行更新,因此 mongodb 发现新旧记录相同,因此 nModified 字段设置为零。

标签: node.js database mongodb mongoose backend


【解决方案1】:

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

update()findById(),找不到 _id,并返回 null,因为 _id 类型可能是您的集合/文档中的字符串, - 请使用 Compass。

【讨论】:

    【解决方案2】:

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

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

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

    【讨论】:

    • 我添加了我想更新的元素,它有不同的值。
    【解决方案3】:

    尝试使用

    isPublished: {
        type: Boolean,
        default: false
    }
    

    而不是

    isPublished: Boolean
    

    【讨论】:

    • 没有工作,同样的结果。我认为这可能是 mongoose 或 mongodb 的问题。
    【解决方案4】:

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

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

    所以你应该通过转换得到想要的结果,像这样:

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

    【讨论】:

      【解决方案5】:

      在您的架构中添加 _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 课程中遇到了同样的问题,这个解决方案对我有用! :)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-05
        • 2016-12-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-14
        • 1970-01-01
        • 2018-10-25
        相关资源
        最近更新 更多