gpt4 book ai didi

node.js - Mongoose .save 函数似乎没有在 node.js 脚本中被调用

转载 作者:太空宇宙 更新时间:2023-11-03 23:30:49 24 4
gpt4 key购买 nike

我是 Node.js 和 mongoose 以及全栈 Web 开发的初学者。我一直在绞尽脑汁地设置数据库并与我的服务器通信,但无法完全让它工作。我一直在宽松地遵循本教程:Easily Develop Node.js and MongoDB Apps with Mongoose

无论如何,我的文件目前组织得非常简单。我的 server.js 与“models”文件夹位于同一目录中,其中包含我的“testSchema.js”文件。

我有一个脚本,可以通过按 server.js 文件中的按钮来调用。

var mongoose = require('mongoose');
var mongoURL = "mongodb://username:password@localhost:27017/test";
mongoose.connect(mongoURL);

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("We have connected");
var Item = require("./models/testSchema");
var newItem = Item({
name: 'Peter',
score: 5
});
newItem.save(function(err) {
if (err) throw err;
console.log("Item Created");
});

});
mongoose.connection.close();

这应该将示例文档添加到我的模型中。最后,testSchema.js:

var Schema = mongoose.Schema;
var ItemSchema = new mongoose.Schema({
name: {
type: String,
index: true
},
score : Number
});

var Item = mongoose.model('Item', ItemSchema);

module.exports = Item;

因此,当我运行脚本时,我收到消息“我们已连接!”,但没有收到消息“项目已创建”,也没有收到调用 .save 函数后出现的任何错误日志。看起来这只是被跳过了,但我不知道 mongoose 和 node.js 在这种情况下的行为如何。 .save 是否会被调用?

另外:我的 mongoDB 数据库托管在 Openshift 上,但我已经将端口转发到本地主机,看起来工作正常。每当我调用脚本时,我都会收到消息“正在处理 27017 的连接”。

任何帮助将不胜感激!

** 编辑 **

我无法发表评论,所以我只能编辑我的帖子。

扎卡里·雅可比 (Zachary Jacobi) 和罗伯特·克莱普 (Robert Klep) 的回答成功了!非常感谢,我不知道 Node 是这样异步的。

最佳答案

Node 在 I/O 上是异步的,因此事情不一定按照它们在代码中出现的顺序发生。

这里数据库连接打开, Node 移动到下一条语句,而无需等待回调中的其余内容完成。所以 mongoose.connection.close(); 实际上是在 newItem.save(function(err) {... 之前执行的。

要解决此问题,请尝试:

var mongoose = require('mongoose');
var mongoURL = "mongodb://username:password@localhost:27017/test";
mongoose.connect(mongoURL);

var db = mongoose.connection;
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function() {
console.log("We have connected");
var Item = require("./models/testSchema");
var newItem = Item({
name: 'Peter',
score: 5
});
newItem.save(function(err) {
if (err) throw err;
console.log("Item Created");
mongoose.connection.close();
});

});

关于node.js - Mongoose .save 函数似乎没有在 node.js 脚本中被调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38467386/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com