我想用给定的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和其他代码进行更新时,结果在控制台中为空:
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 }
课程没有更新。错误在哪里? 请注意,如果我要创建新文档,则不会出现任何问题。
答案 0 :(得分:0)
根据MongoDB update doc,我看不到代码中的任何问题,这里的查询和语法是正确的。
update()方法返回一个WriteResult对象,该对象包含 操作状态。成功后,WriteResult对象将包含 符合查询条件的文档数 更新插入的文档数量以及文档数量 修改。
这里没有文档被修改,唯一的原因是,您要设置相同的数据以在查询中进行更新。
答案 1 :(得分:0)
尝试使用
isPublished: {
type: Boolean,
default: false
}
代替
isPublished: Boolean
答案 2 :(得分: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 }
});
答案 3 :(得分:0)
update({_ id:id},...)指定_id,期望文档中的_id类型为ObjectID。
update()和findById()找不到_id,并返回null,因为_id类型可能是集合/文档中的String,请与Compass一起检查。
答案 4 :(得分: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课程中遇到了相同的问题,该解决方案对我有用! :)