首页 > 解决方案 > 猫鼬中的model.find({})没有给出db.model.find()的输出

问题描述

需要一些帮助,我有以下架构:

var mongoose = require('mongoose');

var categorySchema = new mongoose.Schema({
   name: String 
});

module.exports = mongoose.model('Category', categorySchema);

然后我有一个数组:

var categories = ['Men\'s', 'Women\'s', 'Children\'s', 'Baby\'s'];

然后我运行:

async function addCats() {
    try {
        for (const category of categories){
            Category.create({name:category});
            console.log("Created Category: " + category)
        }
        console.log(Category.find({}));
    }
    catch(err) {
        console.log(err);
    }
}

Category.find({}) 的 console.log 返回了一些疯狂的对象。

但是,如果我进入 mongo 并执行 db.categories.find() 我会得到正确的数据:

{ "_id" : ObjectId("5b4742899146fc1c2bb9837e"), "name" : "Women's", "__v" : 0 }
{ "_id" : ObjectId("5b4742899146fc1c2bb9837d"), "name" : "Men's", "__v" : 0 }
{ "_id" : ObjectId("5b4742899146fc1c2bb98380"), "name" : "Baby's", "__v" : 0 }
{ "_id" : ObjectId("5b4742899146fc1c2bb9837f"), "name" : "Children's", "__v" : 0 }

我觉得我犯了一些愚蠢的错误,但无法弄清楚。

标签: node.jsmongodbmongoose

解决方案


您缺少find(). 你应该使用类似的东西,

Category.find({}, function(err, result){
   console.log(result);
})

您的最终代码变为:

async function addCats() {
  try {
    for (const category of categories){
      Category.create({name:category});
      console.log("Created Category: " + category)
    }
    Category.find({}, function(err, result){
      console.log(result);
    }); 
  }
  catch(err) {
    console.log(err);
  }
}

推荐阅读