Node.js 带有updateOne()的Mongodb upsert选项不起作用

Node.js 带有updateOne()的Mongodb upsert选项不起作用,node.js,angular,mlab,Node.js,Angular,Mlab,我目前正在解决一个问题,而我的代码允许通过*ngFor更新对象数据,但不允许通过updateOne()函数进行upsert 根据其他帖子,添加修饰符$set应该可以解决这个问题,我已经在代码中加入了它,但是没有用 这是我的密码 api.js(后端) 为了更好地理解我的代码是如何工作的,这是将我的api.js连接到我的component.ts的angular服务 服务.ts 有了上面的代码,当我试图更新一个没有_id的对象时,我希望upsert选项能够创建一个新文档。请容忍我,因为我是MEAN的新

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

根据其他帖子,添加修饰符$set应该可以解决这个问题,我已经在代码中加入了它,但是没有用

这是我的密码

api.js(后端)

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

服务.ts

有了上面的代码,当我试图更新一个没有_id的对象时,我希望upsert选项能够创建一个新文档。请容忍我,因为我是MEAN的新手

编辑

console.log(req.body)
给我一个
{header:'header',subheader'subheader'}
的结果,它类似于我数据库中的数据

console.log(结果)
返回:

  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 }
结果:
{n:1,
n修改:1,
opTime:{ts:[时间戳],t:1},
选举ID:7FFFFF0000000001,
好:1,,
操作时间:
时间戳{u bsontype:'Timestamp',低:1,高:1571727952},
“$clusterTime”:{clusterTime:[时间戳],签名:[Object]},
连接:
联系{
_活动:
[对象:空原型]{
错误:[函数],
关闭:[函数],
超时:[函数],
parseError:[函数],
消息:[函数]},
_活动日期:5,,
_maxListeners:未定义,
id:0,
选项:
{主机:'ds259367.mlab.com',
港口:59367,
尺码:5,
minSize:0,
连接超时:30000,
socketTimeout:360000,
基帕利夫:是的,
保持初始延迟:300000,
诺德利:没错,
ssl:false,
checkServerIdentity:true,
ca:空,
crl:null,
证书:空,
key:null,
密码短语:null,
拒绝:错误,
promoteLongs:没错,
推广价值观:正确,
促销员:错,
对,,
重新连接区间:1000,
重新连接:30次,
domainsEnabled:错误,
法律模式:正确,
disconnectHandler:[存储],
cursorFactory:[函数:游标],
错误:是的,
监视器命令:false,
promiseLibrary:[功能:Promise],
clientInfo:[对象],
服务器:[阵列],
是的,
useNewUrlParser:true,
auth:[对象],
authSource:'tawebdb',
dbName:'tawebdb',
socketTimeoutMS:360000,
连接超时:30000,
retryWrites:没错,
是的,
readPreference:[readPreference],
凭证:[MongoCredentials],
bson:bson{},
记录器:记录器{className:'Connection'},
bson:bson{},
标签:未定义,
maxBsonMessageSize:67108864,
港口:59367,
主机:“ds259367.mlab.com”,
socketTimeout:360000,
基帕利夫:是的,
保持初始延迟:300000,
连接超时:30000,
答复:
{promoteLongs:没错,
推广价值观:正确,
promoteBuffers:false},
法拉盛:错,
队列:[],
writeStream:null,
销毁:错误,
哈希名称:“09c68a091568e21c31a31a2ad4f8286db4fb6fb3”,
工作项:[],
插座:
插座{
连接:错,
_haderro:false,
_句柄:[TCP],
_父项:null,
_主机:“ds259367.mlab.com”,
_readableState:[readableState],
可读性:对,
_事件:[对象],
_活动日期:5,,
_maxListeners:未定义,
_可写状态:[可写状态],
可写:对,
AllowAllOpen:错误,
_sockname:null,
_pendingData:null,
_彭丁编码:'',
服务器:空,
_服务器:空,
超时:360000,
[符号(异步ID)]:7,
[符号(LastWriteEqueSize)]:0,
[符号(超时)]:
超时{
_叫:假,,
_空闲时间:360000,
_idlePrev:[计时器列表],
_idleNext:[计时器列表],
_idleStart:14489,
_onTimeout:[函数:绑定],
_计时器:未定义,
_重复:空,
_销毁:错误,
[符号(未反馈)]:正确,
[符号(异步ID)]:1899,
[符号(触发器ID)]:7},
[符号(千字节数)]:0,
[符号(kbyteswrited)]:0},
缓冲区:空,
sizeOfMessage:0,
字节:0,
stubBuffer:null,
伊斯马斯特:
{hosts:[数组],
集合名称:“rs-ds259367”,
设定版本:1,
伊斯马斯特:是的,
第二:错,
主要:“ds259367-a.mlab.com:59367”,
我:“ds259367-a.mlab.com:59367”,
选举ID:7FFFFF0000000001,
lastWrite:[对象],
MaxBSonObject大小:16777216,
maxMessageSizeBytes:48000000,
maxWriteBatchSize:100000,
当地时间:2019-10-22T07:05:40.313Z,
logicalSessionTimeoutMinutes:30,
版本:0,
最大版本:6,
只读:false,
好:1,,
操作时间:[时间戳],
“$clusterTime”:[Object]},
最近一次地震:227},
信息:
BinMsg{
解析:对,
原始:
,
数据:
,
bson:bson{},
选择:
{promoteLongs:没错,
推广价值观:正确,
promoteBuffers:false},
长度:245,
请求ID:166210560,
答复:4,,
操作码:2013年,
fromCompressed:未定义,
响应间隔:0,
检查当前:错误,
莫雷托科姆:错,
允许排气量:false,
promoteLongs:没错,
推广价值观:正确,
促销员:错,
文件:[[对象]],
索引:229,
hashedName:'09c68a091568e2
updateSlide(id: number, newheader: string, subheader: string){
   return this.http.put<any[]>('./api/carousel/update/' + id, {'header': newheader, 'subheader': newsubheader})
}
carousels: any = [];

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

})
}
  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 }
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)
  });
});
updateOne(equal("vendor_id", vendorId),
      inc("views_count", views),
      UpdateOptions().upsert(true))