繁体   English   中英

mongoose 模式字符串类型不工作

[英]mongoose schema string type is not working

我使用 mongoose 创建了一个模式,其中包含一个名为“favoriteFoods”的数组字段。 但是当我检索一个实例并尝试将另一种食物推送到这个数组时,它失败了并显示“TypeError:无法读取未定义的属性'push'”。 我查了一下这个字段的类型,它显示的是“undefined”而不是“array”。 为什么会这样?

const personSchema = new mongoose.Schema({
name: {
    type: String,
    required: true
},
age: Number,
favoriteFoods: [String] //set up the type as an array of string
});

const Person = mongoose.model("Person", personSchema);

new Person({ name: "Lily", age: 5, favoriteFoods: "Vanilla Cake" }).save().catch(e => {
console.log(e);
})

Person.find({ name: "Lily" }, (err, data) => {
if (err) console.log(err);
console.log(data); // it gives me the object
console.log(data.favoriteFoods); // undefined
console.log(typeof (data.favoriteFoods)); // undefined
})

看起来你在说favoriteFoods接受一个字符串数组,但你传递给它的是一个不在数组中的字符串值。 更重要的是,也不能保证你的new Person在你试图find它之前已经完成保存,因为操作是异步发生的

问题已解决!

我做了 2 处更改 -

  1. 将数组传递给favoriteFoods而不是单个值(谢谢@pytth!!)
  2. 将 Model.find() 更改为 Model.findOne() 因为第一个返回数组但第二个返回 object

所以最后的代码是:

const findLily = async () => {
    const lily = new Person({ name: "Lily", age: 5, favoriteFoods: ["Vanilla Cake", "Lollipop"] });
    await lily.save();
    const found = await Person.find({ name: "Lily" });
    found.favoriteFoods.push("hamburger");
    await found.save();
}

如果我有任何错误,请纠正我。 谢谢: :)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM