猫鼬findbyid()返回null
问题描述:
我正在尝试按其ID在mongo数据库中找到一条记录
I am trying to find a record in my mongo db by its id
无论我使用findbyid(),findone(id,...),它都返回null
No matter I use findbyid(), findone(id,...), it return null
这是我的代码.解决办法是什么?
here is my code. what is the solution?
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/Movie', {useNewUrlParser: true})
.then(() => console.log('Connected to Databse'))
.catch(err => console.err('Could not connect to MongoDB', err));
var ObjectId = require('mongodb').ObjectID;
const Schema = new mongoose.Schema({
name: String,
author: String,
tags: [String],
date: Date,
isPublished: Boolean,
price: Number
});
const Data = mongoose.model('Datas', Schema);
async function updateData(id){
const result = await Data.findById(id);
console.log(result);
}
updateData('5a6900fff467be65019a9001');
答
我遇到了同样的问题.我的数据库集合中的_id是String
.启用猫鼬调试require('mongoose').set('debug', true)
后,除非在架构中定义_id
,否则我发现猫鼬查询id
为ObjectId("yourId")
.为了解决该问题,我必须在猫鼬模式中添加_id:String
.
I had the same problem. The _id in my DB collection was a String
. After I enabled mongoose debug require('mongoose').set('debug', true)
, I found out that the mongoose query id
as ObjectId("yourId")
unless we define _id
in the Schema. In order to solve the problem I had to add _id:String
in to mongoose schema.
const MyDataSchema = new Schema({
_id: String,
...
...
}