【发布时间】: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 }
课程没有更新。错误在哪里? 请注意,如果我想创建新文档,它没有问题。
【问题讨论】:
-
author和isPublished是否已经与您尝试设置的值相同? -
嗨。 isPublished 具有相同的值,但作者不同。我尝试过使用其他更新选项,例如通过其 id 查找元素然后更新它,但它不起作用。
-
您正在尝试使用相同的硬编码值进行更新,因此 mongodb 发现新旧记录相同,因此
nModified字段设置为零。
标签: node.js database mongodb mongoose backend