[英]How to update document in mongodb with node js
我正在嘗試使用 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
}
});
更新函數給出這樣的輸出。
{ 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");
}
});
}`
如果您有任何其他問題,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.