简体   繁体   English

mongoose 模式字符串类型不工作

[英]mongoose schema string type is not working

I used mongoose to create a schema that contains an array field called "favoriteFoods".我使用 mongoose 创建了一个模式,其中包含一个名为“favoriteFoods”的数组字段。 But when I retrieved an instance and tried to push another food to this array, it failed and says "TypeError: Cannot read property 'push' of undefined".但是当我检索一个实例并尝试将另一种食物推送到这个数组时,它失败了并显示“TypeError:无法读取未定义的属性'push'”。 I looked up the type of this field, it showed "undefined" instead of "array".我查了一下这个字段的类型,它显示的是“undefined”而不是“array”。 Why is it happening?为什么会这样?

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
})

It looks like you are saying favoriteFoods takes an array of strings, but you are passing it a string value NOT in an array.看起来你在说favoriteFoods接受一个字符串数组,但你传递给它的是一个不在数组中的字符串值。 What's more, there is also no guarantee that your new Person is done being saved before you try to find it since the operation happens asynchronously更重要的是,也不能保证你的new Person在你试图find它之前已经完成保存,因为操作是异步发生的

The problem has been solved!问题已解决!

I made 2 changes -我做了 2 处更改 -

  1. Passing an array to favoriteFoods instead of a single value (Thank you @pytth!!)将数组传递给favoriteFoods而不是单个值(谢谢@pytth!!)
  2. Changing Model.find() to Model.findOne() because the 1st returned an array but the 2nd one returned an object将 Model.find() 更改为 Model.findOne() 因为第一个返回数组但第二个返回 object

So the final code is:所以最后的代码是:

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();
}

Please correct me if I made any mistakes.如果我有任何错误,请纠正我。 Thanks: :)谢谢: :)

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

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