简体   繁体   English

使用 javascript 中的 findByID 从 MongoDB 获取 null ObjectID - 新手

[英]Getting null ObjectID from MongoDB using findByID in javascript - newbie

I am new to javascript and mongo and trying to find a course in my MongoDB database collection using id but getting null.我是 javascript 和 mongo 的新手,并试图使用 id 在我的 MongoDB 数据库集合中找到一门课程,但得到的是 null。 Could you please help me with this?你能帮我解决这个问题吗?

Note: I am using MacBook.注意:我使用的是 MacBook。 This is a very basic thing I am trying to do.这是我正在尝试做的一件非常基本的事情。 I am able to fetch the object using.find() but findByID(id) doesn't seem to work for me.我可以使用.find() 获取 object 但 findByID(id) 似乎对我不起作用。 What am I missing?我错过了什么? Let me know if any more detail is required.让我知道是否需要更多细节。

Edit: A weird observation, refer the image .编辑:一个奇怪的观察,参考图像 For the first one, I cannot find it or update it using id but I could find and update the second one.对于第一个,我找不到它或使用 id 更新它,但我可以找到并更新第二个。 The first one was inserted in database using json file and second one was inserted using.save() in javascript.第一个使用 json 文件插入数据库,第二个使用 javascript 中的.save() 插入。

PFB my code: PFB我的代码:

const mongoose = require('mongoose');

mongoose.connect('mongodb://localhost/mongo-exercise', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('Connected to mongo-exercise database.'))
    .catch(err => console.log('Could not connect to mongo-exercise database.', err));

// Create the schema
const schema = new mongoose.Schema({
    name: String,
    author: String,
    price: Number,
    tags: [String],
    isPublished: Boolean
});

// Call the schema
const Course = mongoose.model('course', schema);

async function updateCourse(id) {
    try {
        const course = await Course
            .findById(id);
        console.log('Course is ', course);
    }
    catch (err) {
        console.log('Solution failed: ', err.message);
        throw error
    }
}

updateCourse("5a68fdf95db93f6477053ddd");

[ [在此处输入图像描述 ] ]

Happened to me.when importing using compass, just deselect the _Id property as its a string.发生在我身上。使用指南针导入时,只需取消选择 _Id 属性作为其字符串。 When imported mongodb driver will put in a new object _id with and objectid that can be queried.当导入 mongodb 驱动程序时,将放入一个新的 object _id 和可以查询的 objectid。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM