gpt4 book ai didi

node.js - Mongoose 更新总是给我 TypeError : Cannot set property '__v' of undefined

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

每当用户断开连接时,我都会尝试将 socketId 更新为“”。但不知何故我总是收到这个错误

update.$setOnInsert[this.schema.options.versionKey] = 0;
^
TypeError: Cannot set property '__v' of undefined

例如,如果有人断开连接,我的目标

socketId = ZH_Ic0zD8QkmNYuJAAAE;
will be
socketId = '';

这是代码

  socket.on('disconnect', function() {
console.log(socket.id);
var disconnectSocketId = '';
User.findOneAndUpdate({socketId: socket.id}, disconnectSocketId, {upsert: true, new: true}, function(err, doc) {
if (err) {
return console.error
}

console.log(doc.socketId);
});
});

最佳答案

您的代码存在一些问题。

更新:将 socket.id 作为 query 对象传递的问题显然已经在您的问题的最新编辑中得到解决。

最重要的是,TypeError 表明显然没有对象 update.$setOnInsert (我知道 this.schema.options.versionKey 包含字符串 ” __v"),因此您尝试将属性分配给 undefined object 。您应该首先以某种方式初始化它:

var update = {
$setOnInsert: {},
$set: {}
...
}

如果我没猜错的话,您希望将 $setOnInsert 对象作为文档对象的一部分传递给 findOneAndUpdate(),对吧?您的函数参数化看起来错误: disconnectSocketId 应该保存带有要更新字段的文档对象,但您只传递了一个空字符串。另外,仅传递 socket.id 作为查询对象看起来也不正确。此外:您确定要通过清除标识符来更新记录...?最后:请注意,如果您使用 $setOnInsert 传递要更新的字段,那么如果您查询的记录已经存在(即具有该 ID),这实际上不会更新您的数据。

假设 update 表示保存有关字段及其应如何更新的信息的对象,我认为您正在尝试执行类似的操作:

User.findOneAndUpdate({ socketId: socket.id }, update, { upsert: true, new: true }, function(err, doc) {
...
}

请务必检查mongoDB docs for $setOnInsertmongoose docs for findOneAndUpdate

关于node.js - Mongoose 更新总是给我 TypeError : Cannot set property '__v' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32434771/

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