Am试图使用node js更新mangodb数据库中的一些数据,但文档不会更新。我收到此日志消息{ n: 0, nModified: 0, ok: 1 }
这是我的代码:
我成功连接到数据
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/cinemas')
.then(()=> console.log('connected to mongoDB....'))
.catch(err => console.log('Could not connect to mongoDB because',err));
这是模式
const moviesSchema = new mongoose.Schema({
title: String,
acotrs:[String],
genre: [String],
date: {type: Date, default: Date.now},
onCinema :Boolean
});
型号连接
const Movie = mongoose.model('Movie',movieSchema);
我可以搜索数据库,没有任何问题,唯一的问题是不更新数据库的更新功能。以下是功能:
async function updateMovie(id){
const result = await Movie.update({_id: id},{
$set:{
title: 'New Movie',
onCinema: false
}
});
console.log(result);
}
updateMovie('5a68fdf95db93f6477053ddd');
我在控制台{ n: 0, nModified: 0, ok: 1 }
上得到这个日志,它告诉我没有更新任何内容。请帮忙。我做错了什么?
const result = await Movie.update({_id: id},{
$set:{
title: 'New Movie',
onCinema: false
}
});
update函数提供这样的输出。
{ n: 0, nModified: 0, ok: 1 }
尝试findByIdAndUpdate
const result = await Movie.findByIdAndUpdate(id,{
$set:{
title: 'New Movie',
onCinema: false
}
});
它将以json格式给出确切的结果。
您给出的id是字符串类型,_id是ObjectId,因此添加mongoose。Types.ObjectId(id(应该可以解决这个问题。
async function updateMovie(id){
const result = await Movie.update({_id: mongoose.Types.ObjectId(id)},{
$set:{
"title": 'New Movie',
"onCinema": false
}
});
console.log(result);
}
updateMovie('5a68fdf95db93f6477053ddd');
试试这个:
`MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {
let queryId = { _id: this.id }; //Get the ID of the object
let myObj = {
$set: {
name: 'Somename' //Whatever you want to change for that ID
}
var db = client.db("database_name");
db.collection("collection_name").updateOne(queryId, myObj, (err, res) => {
if (err) {
console.log("not Updated");
}
else{
console.log("Updated");
}
});
}`
如果你还有其他问题,请告诉我。