node.js - 猫鼬中的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 }
我觉得我犯了一些愚蠢的错误,但无法弄清楚。
解决方案
您缺少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);
}
}
推荐阅读
- react-native - 安装 react-redux 后,native_modules.gradle 文件将被删除
- javascript - 如何在选择框上成功删除数据消息?
- ios - 如何使用GraphicContext快速获得书法线刷效果
- android - 按钮背景的十六进制颜色 - Kivy
- typescript - 声明模块和导入定义
- c# - 错误 CS1514:意外符号“公共”,应为“。” 或'{'
- python - Python Selenium:StaleElementReferenceException / 设置 aria-pressed = "true"
- node.js - 当我在 cmd 中使用 npm start 启动我的反应应用程序时,我收到以下错误
- python - Python多处理不会提高性能
- caching - 为 Cloud CDN 的对象禁用浏览器缓存时出错(通过 Google Cloud Storage 的存储桶)