首先,我编写了在数据库中保存fruit和person文档的代码。然后,我添加了最后几行代码来读取所有fruit文档。下面是我的JavaScript代码:
// getting-started.js
const mongoose = require('mongoose');
main().catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://localhost:27017/test');
// use `await mongoose.connect('mongodb://user:password@localhost:27017/test');` if your database has auth enabled
}
//create a SCHEMA that sets out the fields each document will have and their datatypes
const fruitSchema = new mongoose.Schema({
name: String
});
//create a MODEL
const Fruit = mongoose.model('Fruit', fruitSchema);
//create a DOCUMENT
const fruit = new Fruit({
name: 'Apple',
rating: 7,
review: "Great!"
});
//save the document
fruit.save();
//(we comment it in case you do not want to save the same thing every time)
const personSchema = new mongoose.Schema(
{
name:String,
age:Number,
}
);
const Person = mongoose.model('Person', personSchema);
const person = new Person({
name:"Alice",
age:45
})
//person.save();
const kiwi = new Fruit({
name: 'Kiwi',
score: 10,
review: 'The best fruit!'
});
const orange = new Fruit({
name: 'Orange',
score: 4,
review: 'Too sour for me'
});
const banana = new Fruit({
name: 'Banana',
score: 3,
review: 'Weird texture'
});
/*Fruit.insertMany([kiwi, orange, banana], function(err){
if (err) {
console.log(err);
} else {
console.log('Successfully saved all the fruits to FruitsDB');
}
});*/
Fruit.find(function(err,fruits){
if(err){
console.log(err);
}
else{
console.log(fruits);
}
})
这是我的跑步成绩:
$ node app.js
[
{
_id: new ObjectId("6349856a38dadec09142ade8"),
name: 'Kiwi',
__v: 0
},
{
_id: new ObjectId("6349856a38dadec09142ade9"),
name: 'Orange',
__v: 0
},
{
_id: new ObjectId("6349856a38dadec09142adea"),
name: 'Banana',
__v: 0
},
{
_id: new ObjectId("63498906b285b3fc1887f99f"),
name: 'Apple',
__v: 0
},
{
_id: new ObjectId("63498906b285b3fc1887f9a1"),
name: 'Kiwi',
__v: 0
},
{
_id: new ObjectId("63498906b285b3fc1887f9a2"),
name: 'Orange',
__v: 0
},
{
_id: new ObjectId("63498906b285b3fc1887f9a3"),
name: 'Banana',
__v: 0
},
{
_id: new ObjectId("634a2e34d99e79b07647f88f"),
name: 'Apple',
__v: 0
}
]
你可以看到结果中没有评论和评分。只有名字出现。我想知道为什么会是这样。
1条答案
按热度按时间oyxsuwqo1#
您没有在
Schema
定义中包含does属性。请尝试更改此部分:对此: