首页 > 解决方案 > Mongoose.Model.findById() 返回 null

问题描述

const mongoose =  require('mongoose');
mongoose.connect('mongodb://localhost/mongo-exercises')
        .then(()=>{
            console.log('DataBase Connected..!!');
        })
        .catch(err=> console.log('Connection err: ',err));
const schema = new mongoose.Schema({
    tags:[ String ],
    date:Date,
    name: String,
    author: String,
    isPublished: Boolean,
    price: Number
});
const Course = mongoose.model('course',schema);
async function updateCourse(id){
    const course = await Course.findById(id);
    if(!course) return;
    course.name = "mongo db";
    console.log(course)
    const result = await course.save();
}

updateCourse("5a68fdc3615eda645bc6bdec");      

我的 updateCourse(id) 返回 null。输出::

C:\Users\Divay Mohan\Desktop\100DaysOfCode\Day9\PracticeCRUD>node index.js
DataBase Connected..!!
  mquery findOne courses { _id: 5a68fdc3615eda645bc6bdec } { fields: {} } +0ms

并使用相同的程序::

const mongoose =  require('mongoose');

mongoose.connect('mongodb://localhost/mongo-exercises')
        .then(()=>console.log('DataBase Connected..!!'))
        .catch(err=> console.log('Connection err: ',err));

const schema = mongoose.Schema({
    tags:[ String ],
    date:Date,
    name: String,
    author: String,
    isPublished: Boolean,
    price: Number
});

const Course = mongoose.model('course',schema);
async function getCourses(){
    const result =  await Course.find();
    console.log(result);
}
getCourses();

输出:

C:\Users\Divay Mohan\Desktop\100DaysOfCode\Day9\PracticeCRUD>node exercise3.js
DataBase Connected..!!
[ { tags: [ 'react', 'frontend' ],
    _id: 5a68fdf95db93f6477053ddd,
    date: 2018-01-24T21:43:21.589Z,
    name: 'React Course',
    author: 'Parbhu',
    isPublished: false,
    __v: 0 },
  { tags: [ 'express', 'backend' ],
    _id: 5a68fdc3615eda645bc6bdec,
    date: 2018-01-24T21:42:27.388Z,
    name: 'Express.js Course',
    author: 'DM',
    isPublished: true,
    price: 10,
    __v: 0 },
  { tags: [ 'aspnet', 'backend' ],
    _id: 5a68fde3f09ad7646ddec17e,
    date: 2018-01-24T21:42:59.605Z,
    name: 'ASP.NET MVC Course',
    author: 'Divay',
    isPublished: true,
    price: 15,
    __v: 0 },
  { tags: [ 'node', 'backend' ],
    _id: 5a68ff090c553064a218a547,
    date: 2018-01-24T21:47:53.128Z,
    name: 'Node.js Course by Mohan',
    author: 'Mohan',
    isPublished: false,
    price: 12,
    __v: 0 },
  { tags: [ 'angular', 'frontend' ],
    _id: 5a6900fff467be65019a9001,
    date: 2018-01-24T21:56:15.353Z,
    name: 'Angular Course',
    author: 'kate',
    isPublished: true,
    price: 15,
    __v: 0 },
  { tags: [ 'node', 'backend' ],
    _id: 5a68fdd7bee8ea64649c2777,
    date: 2018-01-24T21:42:47.912Z,
    name: 'Node.js Course',
    author: 'Tom',
    isPublished: true,
    price: 20,
    __v: 0 },
  { tags: [ 'node', 'backend' ],
    _id: 5a68fe2142ae6a6482c4c9cb,
    date: 2018-01-24T21:44:01.075Z,
    name: 'Node.js Course by More',
    author: 'More',
    isPublished: true,
    price: 12,
    __v: 0 } ]

比较两个程序和输出。第一个 Model.find() 工作正常,但 Model.findById() 不工作。这是我现在正在处理的配置:

{
  "name": "PracticeCRUD",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "dependencies": {
    "mongoose": "^5.0.1"
  }
}

  1. npm 版本是 5.5.1
  2. 节点版本是 8.9.4
  3. MongoDB 版本是MongoDB 4.2.6 社区

请帮帮我。谢谢你..

标签: node.jsmongodbnpmmongoose

解决方案


由于您尚未_id在架构中指定类型,因此默认为 type ObjectId。因此,findById数据库中 _id 的值也应该是 type ObjectId。在您的情况下,如果您列出 mongo shell 中的文档_id应该类似于"_id" : ObjectId("5a68fdc3615eda645bc6bdec")

您可以尝试从您的代码创建记录并尝试查询它吗

let c = new Course({ "tags": [ 'express', 'backend' ],     date: "2018-01-24T21:42:27.388Z",     "name": 'Express.js Course',     "author": 'Mosh',     "isPublished": true,     "price": 10})
c.save((err, result) => {
    if (err) console.log(err);
    console.log("new record added: " + result);
  });

推荐阅读