我正在尝试将"switch"替换为"on",但它是"关闭",并试图在我的数据库中立即将文档替换为id"1",这是一个屏幕截图。 https://i.stack.imgur.com/0zWdm.jpg。我不知道该怎么做,因为我是猫鼬的新手。
这是我的架构。
const mongoose = require('mongoose');
const switchSchema = mongoose.Schema({
_id: Number,
switch: String
});
module.exports = mongoose.model('switch', switchSchema)
还有我的索引.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;
}