node.js - Mongoose 创建后查找方法

标签 node.js mongoose mongoose-schema

我有一个动物模式:

const AnimalSchema = new mongoose.Schema({
    type: { type: String, default: "goldfish" },
    size: String,
    color: { type: String, default: "golden" },
    mass: { type: Number, default: 0.007 },
    name: { type: String, default: "Angela" }
});

动物数据数组:

let animalData = [
    {
        type: 'mouse',
        color: 'gray',
        mass: 0.035,
        name: 'Marvin'
    },
    {
        type: 'nutria',
        color: 'brown',
        mass: 6.35,
        name: 'Gretchen'
    },
    {
        type: 'wolf',
        color: 'gray',
        mass: 45,
        name: 'Iris'
    }
];

然后我尝试清空动物模型中的所有数据,将该数组保存到数据库,记录一些动物数据并关闭连接:

Animal
    .remove({})
    .then(Animal.create(animalData))
    .then(Animal.find({}).exec())
    .then(animals => {
        animals.forEach(animal => console.log(`${animal.name} is ${animal.color} ${animal.type}`))
    })
    .then(() => {
        console.log('Saved!');
        db.close().then(() => console.log('db connection closed'));
    })
    .catch((err) => {
        console.error("Save Failed", err);
    });

但是当我尝试执行此操作时,出现错误: 保存失败类型错误:animals.forEach 不是函数 在 Animal.remove.then.then.then.animals (C:_projects\express_api\mongoose_sandbox.js:89:12)

我的代码有什么问题以及如何让它工作?谢谢。

最佳答案

好的,这是一个简单的修复。 需要编写我的 .then() 方法:

Animal
    .remove({})
    .then(Animal.create(animalData))
    .then(Animal.find({}).exec())

喜欢:

Animal
    .remove({})
    .then(() => Animal.create(animalData))
    .then(() => Animal.find({}))

所以在then方法中需要传递一个回调函数。

关于node.js - Mongoose 创建后查找方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44679240/

相关文章:

node.js - NodeJS : How do I unit test an Async function that depends on other Async calls

typescript - 错误 TS2339 : Property 'coord' does not exist on type 'Mixed'

javascript - 如何从 Mongoose 顺序检索数据?

node.js - 文章的 Mongoose 架构

python - 在nodejs和Python之间交换数据

javascript - 使用 'opn' npm 模块在 Docker 中未处理的 promise 拒绝

node.js - 带有 Node js 的谷歌 oauth2

javascript - Node.js:在文本文件中的特定行之后插入一行?

javascript - Mongoose自动改变值的类型

arrays - 从 Mongoose 数组中删除元素