簡體   English   中英

如何替換 mongoose 文檔中的文本?

[英]How could I replace the text in my document in mongoose?

我正在嘗試將“switch”替換為“on”,但它是“off”,並嘗試在我的數據庫中將文檔替換為 id“1”,這是一個屏幕截圖。 https://imgur.com/a/oE0t3Yc 我不知道該怎么做,因為我是 mongoose 的新手。

這是我的架構。

const mongoose = require('mongoose');

const switchSchema = mongoose.Schema({
    _id: Number,
    switch: String
  });

module.exports = mongoose.model('switch', switchSchema)

還有我的 index.js

async function switchon(){
  const replace = await cmdlogging.findOneAndUpdate(
    { switch: 'on' },
    { new: true }
  );
  await replace.findById(1);
}

錯誤是:

UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'findById' of null

findOneAndUpdate需要一個filter來匹配您的文檔作為第一個參數-因此在您的情況下-當您嘗試使用id 1 更新文檔時-您應該將其更改為:

async function switchon(){
  const updatedDocument = await cmdlogging.findOneAndUpdate(
    { _id: 1 },
    { switch: 'on' },
    { new: true }
  );
  // there's no need to call `findById` again, 
  // as replace holds already the updated document, since you've set { new:true } 
 return updatedDocument;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM