Nodejs 中 mongodb 的文档为什么总是更新不成功?

Nodejs 中 mongodb 的文档为什么总是更新不成功?

这里是我在 shell 中的命令

> use ajax
switched to db ajax

> db.posts.find()
{ "_id" : ObjectId("510f1ac5f3cdbff610e7ff56"), "post_title" : "xinlangweibo" }
> db.posts.update({_id:"510f1ac5f3cdbff610e7ff56"},{"post_title":"sina"});
> db.posts.find()
{ "_id" : ObjectId("510f1ac5f3cdbff610e7ff56"), "post_title" : "xinlangweibo" }

> db.posts.update({_id:"510f1ac5f3cdbff610e7ff56"},{post_title:"sina"});
> db.posts.find()
{ "_id" : ObjectId("510f1ac5f3cdbff610e7ff56"), "post_title" : "xinlangweibo" }

使用了这么两种形式的更新,都不成功。

第一种 post_title 没有双引号,第二种有呢,都不成功。

麻烦大家帮忙看下,到底哪里的问题。


3 回复

在 Node.js 中使用 MongoDB 更新文档时,遇到问题可能是由于多种原因导致的。我们可以通过检查代码来定位问题,并提供一些解决方案。

可能的原因及解决方案

  1. 数据类型不匹配

    • 在 MongoDB 中,_id 字段是一个 ObjectId 类型的对象,而不是字符串。
    • 确保你在查询文档时使用的是正确的数据类型。
  2. 更新操作符的使用

    • 如果你只是想简单地更新一个字段,确保使用了正确的更新操作符。

示例代码

假设你正在使用 mongodb 驱动程序(例如 mongodbmongoose),以下是一些可能的解决方案:

使用 mongodb 驱动程序

const { MongoClient } = require('mongodb');

async function updateDocument() {
    const uri = 'your_mongodb_connection_string';
    const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

    try {
        await client.connect();
        const database = client.db('ajax');
        const collection = database.collection('posts');

        // 使用正确的数据类型
        const filter = { _id: new MongoClient(). BSON.ObjectId("510f1ac5f3cdbff610e7ff56") };
        const updateDoc = { $set: { post_title: "sina" } };

        const result = await collection.updateOne(filter, updateDoc);
        console.log(`Updated ${result.modifiedCount} document(s)`);
    } finally {
        await client.close();
    }
}

updateDocument().catch(console.error);

使用 mongoose 驱动程序

const mongoose = require('mongoose');

mongoose.connect('your_mongodb_connection_string', { useNewUrlParser: true, useUnifiedTopology: true });

const PostSchema = new mongoose.Schema({
    post_title: String,
});

const Post = mongoose.model('Post', PostSchema);

async function updateDocument() {
    try {
        const filter = { _id: mongoose.Types.ObjectId("510f1ac5f3cdbff610e7ff56") };
        const updateDoc = { post_title: "sina" };

        const result = await Post.updateOne(filter, updateDoc);
        console.log(`Updated ${result.modifiedCount} document(s)`);
    } catch (error) {
        console.error(error);
    } finally {
        mongoose.disconnect();
    }
}

updateDocument().catch(console.error);

解释

  • 数据类型:在 MongoDB 中,_id 是一个 ObjectId 对象,而不是字符串。因此,在查询时需要使用正确的数据类型。
  • 更新操作符:使用 $set 操作符可以确保只更新指定的字段,而不会替换整个文档。
  • 错误处理:在实际应用中,应该添加适当的错误处理机制,以确保在发生错误时能够捕获并处理。

通过以上代码示例,你可以更好地理解如何正确地进行文档更新操作。


找到问题了,原来是我用错了。

db.posts.update({_id:ObjectId("510f1ac5f3cdbff610e7ff56")},{post_title:"sina"});

应该是这样子。

在 Node.js 中使用 MongoDB 更新文档时遇到问题,通常是因为数据类型不匹配或者方法使用不当。在你的例子中,_id 是一个 ObjectId 类型的对象,而不是字符串。因此,在查询时应该使用正确的类型。

以下是一个示例代码,展示如何正确地进行更新操作:

const { MongoClient } = require('mongodb');

async function updatePost() {
    const uri = "your_mongodb_connection_string";
    const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true });

    try {
        await client.connect();
        const database = client.db('ajax');
        const postsCollection = database.collection('posts');

        // 使用正确的 ObjectId 类型
        const id = '510f1ac5f3cdbff610e7ff56';
        const filter = { _id: new mongoose.Types.ObjectId(id) };
        const updateDoc = {
            $set: {
                post_title: 'sina'
            },
        };

        const result = await postsCollection.updateOne(filter, updateDoc);
        console.log(`Matched ${result.matchedCount} documents and updated ${result.modifiedCount} documents`);
    } finally {
        await client.close();
    }
}

updatePost().catch(console.error);

解释:

  1. 使用正确的 ObjectId 类型:在 MongoDB 中,_id 通常是 ObjectId 类型,而不是字符串。你需要使用 mongoose.Types.ObjectId 来创建正确的 ObjectId 对象。
  2. 使用 $set 更新操作符$set 操作符用于更新指定的字段。
  3. 检查返回结果:通过 result.matchedCountresult.modifiedCount 可以确认是否成功匹配和更新了文档。

如果你没有使用 Mongoose,可以去掉 mongoose.Types.ObjectId,直接使用 new ObjectId(id)

const { MongoClient, ObjectId } = require('mongodb');

确保你已经安装了 mongodb 包,并且连接字符串正确。希望这能帮助你解决问题。

回到顶部