Nodejs Mongodb 置空数组报错

Nodejs Mongodb 置空数组报错

this.update({ “_id” : uid }, {“auth”:[]}, function(err,user) { callback(err,user); })

[TypeError: Cannot read property ‘schema’ of undefined]

为什么不能重置auth 字段?

2 回复

在使用 Node.js 和 MongoDB 更新文档时,如果遇到 TypeError: Cannot read property 'schema' of undefined 错误,通常是因为你在更新操作中没有正确地指定更新的选项。让我们看看如何解决这个问题。

问题分析

你尝试将一个用户文档中的 auth 字段设置为空数组,但是遇到了错误。错误信息表明在某个地方试图访问未定义对象的属性。这可能是因为你在更新操作中没有正确地指定更新的选项。

解决方案

你可以使用 MongoDB 的 updateOneupdateMany 方法来更新文档,并确保正确地指定了更新的选项。以下是使用 updateOne 方法的示例代码:

const mongoose = require('mongoose');
const User = mongoose.model('User', new mongoose.Schema({}));

async function resetAuthField(uid, callback) {
    try {
        // 使用 updateOne 方法更新单个文档
        await User.updateOne(
            { _id: uid }, // 查询条件
            { $set: { auth: [] } }, // 更新操作
            { upsert: false } // 更新选项
        );
        callback(null, "成功重置 auth 字段");
    } catch (err) {
        callback(err, null);
    }
}

// 示例调用
resetAuthField('someUserId', (err, result) => {
    if (err) {
        console.error(err);
    } else {
        console.log(result); // 输出: 成功重置 auth 字段
    }
});

解释

  1. 查询条件{ _id: uid } 用于查找特定的文档。
  2. 更新操作{ $set: { auth: [] } } 表示将 auth 字段设置为空数组。
  3. 更新选项{ upsert: false } 表示如果找不到匹配的文档,则不插入新文档(默认行为)。

通过这种方式,你可以避免遇到 Cannot read property 'schema' of undefined 这样的错误,并且能够正确地重置 auth 字段。


从错误信息 [TypeError: Cannot read property 'schema' of undefined] 可以看出问题可能出在更新操作中使用的模型对象上。这通常意味着你尝试更新的模型实例没有正确初始化或加载。

假设你使用的是 mongoose 库来操作 MongoDB 数据库,以下是一个解决这个问题的方法:

  1. 确保你已经正确加载了对应的模型。
  2. 使用 findOneAndUpdate 方法而不是直接更新。

示例代码:

const mongoose = require('mongoose');
const User = mongoose.model('User', new mongoose.Schema({ auth: [] })); // 定义模型

async function updateUser(uid, callback) {
    try {
        const result = await User.findOneAndUpdate(
            { "_id": uid },
            { "$set": { "auth": [] } }, // 使用 $set 操作符
            { new: true } // 返回更新后的文档
        );
        callback(null, result);
    } catch (err) {
        callback(err, null);
    }
}

// 调用函数
updateUser("someUserId", (err, user) => {
    if (err) console.error(err);
    else console.log(user);
});

在这个示例中:

  • 我们定义了一个名为 User 的 Mongoose 模型。
  • 使用 findOneAndUpdate 方法进行更新操作,并使用 $set 操作符将 auth 字段设置为空数组。
  • 设置 { new: true } 选项来获取更新后的文档。

这样可以避免直接更新时可能遇到的错误,并确保数据被正确更新。

回到顶部