预先感谢您关注这个非常基本的问题!我目前正在从事一个涉及Node,MongoDB和Mongoose(here's my Glitch project)的FreeCodeCamp项目,我对在Mongoose模型上调用.save()
时发生的事情感到非常困惑。您可以在Glitch上看到完整的上下文,但这是我不希望其表现的特定部分:
const { User } = require("./models/user");
...
app.post("/api/exercise/new-user", (req, res) => {
var newUser = new User({ name: req.body.username });
newUser.save((error) => console.error(error));
res.json({username: newUser.name, _id: newUser._id})
});
这里是models/user.js
:
const mongoose = require("mongoose");
exports.User = mongoose.model(
"User",
new mongoose.Schema({
name: { type: String, required: true }
})
);
我在浏览器中看到了我期望的信息的JSON响应,但是在MongoDB上的数据库中没有看到新的文档。我在这里想念什么?据我所知,当我在.save()
上调用newUser
时,该文档应显示在MongoDB中。在以前的项目中,我只是这样做,而且还在工作,我无法弄清楚这种情况下有什么不同。
在FCC课程中,我没有想到的一个更广泛的问题是:Mongoose在MongoDB中创建集合的时间是什么时候?创建新模型时是吗?就像此时在我的代码中一样:
const mongoose = require("mongoose");
exports.User = mongoose.model(
"User",
new mongoose.Schema({
name: { type: String, required: true }
})
);
还是在我去保存模型实例时发生? MongoDB何时被告知创建集合?提前非常感谢!
答案 0 :(得分:0)
好吧,我又做了一次,答案很简单。我看到我在mongoose.connect()
调用中遇到了错误,因为它遇到了以mongodb+srv://
开头的URI,而不仅仅是mongodb://
的URI。然后我看到,因为我是从FCC分叉启动项目的,所以它具有一些过时的Mongoose和MongoDB版本,只需将这两个版本更新为最新版本(MongoDB 3.5.7和Mongoose 5.9.12)即可解决问题,现在我可以正确保存文档了!