猫鼬findbyid()返回null [英] Mongoose findbyid() return null

查看:247
本文介绍了猫鼬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,否则我发现猫鼬查询idObjectId("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,
...
...
}

这篇关于猫鼬findbyid()返回null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆