【发布时间】:2021-10-29 16:44:17
【问题描述】:
这个想法很简单。我在“fruitsDB”内的“fruits”集合中添加了 4 个条目。当我运行 server.js 时,它实际上将列表条目添加到数据库中。
当我检查数据库时,它说我有 4 个条目 [苹果、猕猴桃、橙子、香蕉]。但是 find 方法是
Fruit.find(function(err, fruits){
if(err){
console.log(err);
} else {
console.log(fruits);
} });
当我第一次运行 server.js 时返回一个空数组。如果我第二次运行 server.js 并检查 MongoDB 内部的集合,因为这是第二次运行新的集合内容显示如下
[苹果、猕猴桃、橙子、香蕉、苹果、猕猴桃、橙子、香蕉]
这次 find() 方法显示了数组,但只有 4 个……我在这里做错了什么?
Server.js:
const mongoose = require('mongoose');
main().catch(err => console.log(err));
// This section means connect to mongodb and create fruitsDB database inside that
async function main() {
await mongoose.connect('mongodb://localhost:27017/fruitsDB');
}
const fruitSchema = new mongoose.Schema({
name: String,
rating: Number,
review: String
});
const Fruit = mongoose.model('Fruit', fruitSchema);
// MongoDB will automatically pluralize the collection name
// const fruit = new Fruit({
// name: 'Apple',
// rating: 7,
// review: 'Pretty solid as fruit!'
// });
// Comment out this section to prevent mongoose to
// save fruit to fruits collection everytime you run server.js
// fruit.save();
const peopleSchema = new mongoose.Schema({
name: String,
age: Number
});
const People = mongoose.model('People', peopleSchema);
const people = new People({
name: 'John',
age: 37
});
people.save();
const apple = new Fruit({
name: 'Apple',
rating: 7,
review: 'Pretty solid as fruit!'
});
const kiwi = new Fruit({
name: 'Kiwi',
rating: 10,
review: 'The best fruit!'
});
const orange = new Fruit({
name: 'Orange',
rating: 4,
review: 'Too sour for me!'
});
const banana = new Fruit({
name: 'Banana',
rating: 3,
review: 'Weird texture!'
});
Fruit.insertMany([apple, kiwi, orange, banana], function(error){
if(error){
console.log(error);
} else {
console.log('New entries are added to the database!');
}
});
// Read the fruits collection
Fruit.find(function(err, fruits){
if(err){
console.log(err);
} else {
console.log(fruits);
}
});
【问题讨论】:
标签: javascript node.js mongodb mongoose methods