mongoose 通过 _id 查询

664 阅读1分钟

mongoose 的 find() 可传的参数是 对象 或 ObjectId

Query filter must be a plain object or ObjectId

用 {_id: id} 不行,直接传字符串 id 也不行,字符串的 id 要转换为 ObjectId,引入 mongoose 用 mongoose.Types.ObjectId

mongoose.Types.ObjectId 是类构造函数

Class constructor ObjectId cannot be invoked without 'new'

const mongoose = require('mongoose');

const id = '64986b5c28a25bbf09a6d12f';
const oid = new mongoose.Types.ObjectId(id);

// 查询
略略略.find(oid);