gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-03 22:10:10 24 4
gpt4 key购买 nike

我有一个动物模式:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com