用mongoClient _id替换replaceOne()

时间:2019-06-18 18:00:05

标签: node.js mongodb

Strugglin自2天以来,观看了成堆的stackoveflow帖子,replaceOne()仍然无法通过_id使用。

无论我是否通过对象转换_id,它都不会起作用。 对我而言,唯一的方法是在更新之前删除_id。

我的版本:

{
  "name": "geretonequipesnode",
  "version": "1.0.0",
  "main": "app.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "description": "",
  "dependencies": {
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "express-mongo-db": "^2.0.4",
    "mongodb": "^3.2.7",
  }
}

这是我的node.js代码,请注意,'我正在尝试转换,并且在typeof()函数期间什么都没有显示:

const express = require('express')
const app = express()
var mongodb = require('mongodb');
const { MongoClient, ObjectID } = require('mongodb');
var url ="mongodb://localhost:27017"

app.post('/updateClub', function (req, res) {


    myClub = req.body;


    MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {


        var db = client.db('myDb');

        var ObjectId = require('mongodb').ObjectID; //working
        var idObj = ObjectId(myClub._id); //working
        typeof(idObj); // Nothing on screen

        try {
        db.collection('clubs').replaceOne({'_id':idObj},myClub)
        } catch (e){
           console.log(e);
        }
    })
})

这是错误消息:

(node:3948) UnhandledPromiseRejectionWarning: MongoError: After applying the update, the (immutable) field '_id' was found to have been altered to _id: "5d07e982a7d75a67d6383d6d"

编辑:已解决!!

添加了删除myClub._id; !请看它是如此奇怪;我真的不明白为什么我必须这样做,但是这是合乎逻辑的,因为myClub对象仍然包含_id,所以它生成了一个错误! !

const express = require('express')
    const app = express()
    var mongodb = require('mongodb');
    const { MongoClient, ObjectID } = require('mongodb');
    var url ="mongodb://localhost:27017"

    app.post('/updateClub', function (req, res) {


        myClub = req.body;


        MongoClient.connect(url, { useNewUrlParser: true }, (err, client) => {


            var db = client.db('myDb');

            var ObjectId = require('mongodb').ObjectID; //working
            var idObj = ObjectId(myClub._id); //working
            typeof(idObj); // Nothing on screen
            delete myClub._id;
            try {
            db.collection('clubs').replaceOne({'_id':idObj},myClub)
            } catch (e){
               console.log(e);
            }
        })
    })

0 个答案:

没有答案