gpt4 book ai didi

node.js - mongodb update() 不起作用

转载 作者:太空宇宙 更新时间:2023-11-04 00:59:28 25 4
gpt4 key购买 nike

首先我创建了 Mongoose 模式:

var cardSchema = mongoose.Schema({
userId: String,
imageUrl: String
})

然后我定义了模型:

var Card = mongoose.model('Card', cardSchema)

然后我创建了一张新卡:

var newCard = new Card({
userId: "bablaba"
});

然后新卡就正确保存了(我测试过):

newCard.save(function(err,theCard){
if(err) return console.log(err);
console.log("saved");
console.log(theCard);
})

现在我需要更新卡中的信息。我想将 imageUrl 添加/插入到保存的新卡中。以下是我尝试过的几种方法:

1.

Card.where({ _id: _id }).update({
$set: {imageUrl:"blablab"}
});

2.

Card.update(_id,{$set:{imageUrl:"balbalab"}})

3.

Card.update({_id: updateInfo._id}, {note0:updateInfo.note0, note1: updateInfo.note1},{multi:true}, function(err, numberAffected){});

这三个都不起作用!请帮忙..

最佳答案

根据docs ,

The operation is only executed when a callback is passed. To force execution without a callback (which would be an unsafe write), we must first call update() and then execute it by using the exec() method.

在第一种情况下您缺少回调函数。

Card.where({ _id: "54a108be506225c82a56848b" }).update({
$set: {imageUrl:"blablab"}
},function(e,n){
console.log(n);
});

或者,

Card.update({_id: "54a108be506225c82a56848b"}, 
{"imageUrl":"Hello"},
{multi:true},
function(err, numberAffected){});

关于node.js - mongodb update() 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27684989/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com