【问题标题】:Mongoose find method after create创建后的猫鼬查找方法
【发布时间】:2017-06-21 23:19:10
【问题描述】:

我有一个动物模式:

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 模型中的所有数据,将该数组保存到数据库,记录一些动物数据并关闭连接:

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)

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

【问题讨论】:

    标签: node.js mongoose mongoose-schema


    【解决方案1】:

    好的,这很容易解决。 它需要编写我的 .then() 方法:

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

    喜欢:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-30
      • 2020-11-29
      • 2020-02-28
      • 2021-04-16
      • 2015-11-18
      • 2019-01-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多