【问题标题】:Mongodb upsert option with updateOne() does not work带有 updateOne() 的 Mongodb upsert 选项不起作用
【发布时间】:2020-02-18 03:55:39
【问题描述】:

我目前正在解决一个问题,而我的代码允许通过 *ngFor 更新对象数据,但不允许通过 updateOne() 函数进行更新插入。

根据其他帖子,添加修饰符 $set 应该可以解决问题,我已经将其合并到我的代码中但无济于事。

这是我的代码。

api.js(后端)

router.route('carousel/update/:_id').put(function(req, res) {

  db.collection('home').updateOne({"_id": ObjectId(req.params._id)}, 
  {$set: req.body}, {upsert: true}, (err, results) => {
    if (err) throw err;
    res.send(results)

    console.log(results)
    console.log(req.params._id)
  });
});

为了了解我的代码如何更好地工作,这是将我的 api.js 连接到我的 component.ts 的角度服务。

service.ts

updateSlide(id: number, newheader: string, subheader: string){
   return this.http.put<any[]>('./api/carousel/update/' + id, {'header': newheader, 'subheader': newsubheader})
}

最后,我的 component.ts 文件。

component.ts

carousels: any = [];

updateSlide(id: number){
  this.HomeService.updateSlide(id, this.header, this.subheader).subscribe(slides => {
this.carousels = slides;
console.log(slides)

})
}

使用上面的代码,当我尝试更新没有 _id 的对象时,我希望 upsert 选项创建一个新文档。请多多包涵,因为我是 MEAN 的新手!

编辑

console.log(req.body) 给我一个{header: 'header', subheader 'subheader'} 的结果,这与我数据库中的数据相似。

console.log(results)返回:

  result:
   { n: 1,
     nModified: 1,
     opTime: { ts: [Timestamp], t: 1 },
     electionId: 7fffffff0000000000000001,
     ok: 1,
     operationTime:
      Timestamp { _bsontype: 'Timestamp', low_: 1, high_: 1571727952 },
     '$clusterTime': { clusterTime: [Timestamp], signature: [Object] } },
  connection:
   Connection {
     _events:
      [Object: null prototype] {
        error: [Function],
        close: [Function],
        timeout: [Function],
        parseError: [Function],
        message: [Function] },
     _eventsCount: 5,
     _maxListeners: undefined,
     id: 0,
     options:
      { host: 'ds259367.mlab.com',
        port: 59367,
        size: 5,
        minSize: 0,
        connectionTimeout: 30000,
        socketTimeout: 360000,
        keepAlive: true,
        keepAliveInitialDelay: 300000,
        noDelay: true,
        ssl: false,
        checkServerIdentity: true,
        ca: null,
        crl: null,
        cert: null,
        key: null,
        passphrase: null,
        rejectUnauthorized: false,
        promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false,
        reconnect: true,
        reconnectInterval: 1000,
        reconnectTries: 30,
        domainsEnabled: false,
        legacyCompatMode: true,
        disconnectHandler: [Store],
        cursorFactory: [Function: Cursor],
        emitError: true,
        monitorCommands: false,
        promiseLibrary: [Function: Promise],
        clientInfo: [Object],
        servers: [Array],
        caseTranslate: true,
        useNewUrlParser: true,
        auth: [Object],
        authSource: 'tawebdb',
        dbName: 'tawebdb',
        socketTimeoutMS: 360000,
        connectTimeoutMS: 30000,
        retryWrites: true,
        useRecoveryToken: true,
        readPreference: [ReadPreference],
        credentials: [MongoCredentials],
        bson: BSON {} },
     logger: Logger { className: 'Connection' },
     bson: BSON {},
     tag: undefined,
     maxBsonMessageSize: 67108864,
     port: 59367,
     host: 'ds259367.mlab.com',
     socketTimeout: 360000,
     keepAlive: true,
     keepAliveInitialDelay: 300000,
     connectionTimeout: 30000,
     responseOptions:
      { promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false },
     flushing: false,
     queue: [],
     writeStream: null,
     destroyed: false,
     hashedName: '09c68a091568e21c31a31a2ad4f8286db4fb6fb3',
     workItems: [],
     socket:
      Socket {
        connecting: false,
        _hadError: false,
        _handle: [TCP],
        _parent: null,
        _host: 'ds259367.mlab.com',
        _readableState: [ReadableState],
        readable: true,
        _events: [Object],
        _eventsCount: 5,
        _maxListeners: undefined,
        _writableState: [WritableState],
        writable: true,
        allowHalfOpen: false,
        _sockname: null,
        _pendingData: null,
        _pendingEncoding: '',
        server: null,
        _server: null,
        timeout: 360000,
        [Symbol(asyncId)]: 7,
        [Symbol(lastWriteQueueSize)]: 0,
        [Symbol(timeout)]:
         Timeout {
           _called: false,
           _idleTimeout: 360000,
           _idlePrev: [TimersList],
           _idleNext: [TimersList],
           _idleStart: 14489,
           _onTimeout: [Function: bound ],
           _timerArgs: undefined,
           _repeat: null,
           _destroyed: false,
           [Symbol(unrefed)]: true,
           [Symbol(asyncId)]: 1899,
           [Symbol(triggerId)]: 7 },
        [Symbol(kBytesRead)]: 0,
        [Symbol(kBytesWritten)]: 0 },
     buffer: null,
     sizeOfMessage: 0,
     bytesRead: 0,
     stubBuffer: null,
     ismaster:
      { hosts: [Array],
        setName: 'rs-ds259367',
        setVersion: 1,
        ismaster: true,
        secondary: false,
        primary: 'ds259367-a.mlab.com:59367',
        me: 'ds259367-a.mlab.com:59367',
        electionId: 7fffffff0000000000000001,
        lastWrite: [Object],
        maxBsonObjectSize: 16777216,
        maxMessageSizeBytes: 48000000,
        maxWriteBatchSize: 100000,
        localTime: 2019-10-22T07:05:40.313Z,
        logicalSessionTimeoutMinutes: 30,
        minWireVersion: 0,
        maxWireVersion: 6,
        readOnly: false,
        ok: 1,
        operationTime: [Timestamp],
        '$clusterTime': [Object] },
     lastIsMasterMS: 227 },
  message:
   BinMsg {
     parsed: true,
     raw:
      <Buffer f5 00 00 00 00 2c e8 09 04 00 00 00 dd 07 00 00 00 00 00 00 00 e0 00 00 00 10 6e 00 01 00 00 00 10 6e 4d 6f 64 69 66 69 65 64 00 01 00 00 00 03 6f 70 ... >,
     data:
      <Buffer 00 00 00 00 00 e0 00 00 00 10 6e 00 01 00 00 00 10 6e 4d 6f 64 69 66 69 65 64 00 01 00 00 00 03 6f 70 54 69 6d 65 00 1c 00 00 00 11 74 73 00 01 00 00 ... >,
     bson: BSON {},
     opts:
      { promoteLongs: true,
        promoteValues: true,
        promoteBuffers: false },
     length: 245,
     requestId: 166210560,
     responseTo: 4,
     opCode: 2013,
     fromCompressed: undefined,
     responseFlags: 0,
     checksumPresent: false,
     moreToCome: false,
     exhaustAllowed: false,
     promoteLongs: true,
     promoteValues: true,
     promoteBuffers: false,
     documents: [ [Object] ],
     index: 229,
     hashedName: '09c68a091568e21c31a31a2ad4f8286db4fb6fb3' },
  modifiedCount: 1,
  upsertedId: null,
  upsertedCount: 0,
  matchedCount: 1 }

【问题讨论】:

  • 什么意思?你想让我控制台记录一下吗?
  • 给我一点时间来提供一个编辑过的答案谢谢!
  • 嗨@Subburaj 我已经从console.log 添加了结果。希望对您有所帮助。
  • 当我记录 req.params._id 时,我得到了使用更新函数调用的对象的 _id 的值。所以值取决于我更新的对象。更新任何对象都会记录其 _id。
  • @Subburaj 有什么想法吗?

标签: node.js angular mlab


【解决方案1】:

您必须检查以下条件:

router.route('carousel/update/:_id').put(function(req, res) {
var id;
if(req.params._id == 'undefined')
  {
     id = '';. --------> have to careful there should not be any document with id='' in yourDB at any case
  } else {
    id = ObjectId(req.params._id)
  }

  db.collection('home').updateOne({"_id": id}, 
  {$set: req.body}, {upsert: true}, (err, results) => {
    if (err) throw err;
    res.send(results)

    console.log(results)
    console.log(req.params._id)
  });
});

【讨论】:

  • @Isaac Agatep 你能发布你的req.params._id吗?当您不传递_id时可能会有所不同
  • console.log(req.params._id) 如果对象具有 _id,则返回 {_id: 5d9d84...........}。但是,如果没有找到_id,它会抛出错误。
  • @Isaac Agatep 你需要那个确切的错误..无论是undefined。你必须用 if 条件替换它,所以如果 _id 没有找到,我需要确切的值
  • 如果没有找到_id,它只返回undefined
  • @Isaac Agatep 我已经更新了我的答案。尝试上述方法
【解决方案2】:

导入,

导入 org.mongodb.scala.model.UpdateOptions 并尝试这样::

updateOne(equal("vendor_id", vendorId),
      inc("views_count", views),
      UpdateOptions().upsert(true))

【讨论】:

    猜你喜欢
    • 2020-09-04
    • 2020-09-06
    • 1970-01-01
    • 2018-05-19
    • 2018-05-29
    • 1970-01-01
    • 1970-01-01
    • 2015-11-30
    • 1970-01-01
    相关资源
    最近更新 更多