我正在尝试将“开关”替换为“打开”,但它是“关闭”,并尝试替换id为“1”的文档,现在在我的数据库中,这里是一个屏幕截图。 https://imgur.com/a/oe0t3yc。 我不知道怎么做因为我是猫鼬新手。
这是我的模式。
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;
}