为什么collection.replaceOne后我res.statusCode从200改为404?
出于某种原因,打完电话后
collection.replaceOne({_id: newObj._id}, newObj)
res.statusCode从200 OK到404未找到变化。什么会导致这个问题?这里是我的代码:
const updatePost = (req, res, next) => {
const { user } = req.session;
const params = req.body;
const collection = req.conn.db(db).collection('posts');
try {
const err = new Error();
const [post] = await collection.find({ _id: new ObjectID(params._id) }).toArray();
// some logic for checking params values
await collection.replaceOne({ _id: new ObjectID(params.id) }, post);
res.send({ error: false, message: 'Post updated.' });
return next();
} catch (err) {
return next(err);
}
};
它应该在DB更换文档,但由于某些原因,它抛出的错误与404的响应。为什么会这样呢?
回答如下:如果下面的代码是try块内?
const collection = req.conn.db(db).collection('posts');