如何使用Node JS将mongoDB查询logging到terminal

我正在使用下面的代码添加架构模型到我的数据库…

db.on('error', console.error); db.once('open', function() { var Schema = new mongoose.Schema( name: String, _id: String }); var User = mongoose.model('User', Schema); new User({ name: "Help me!", _id: "12345" }).save(function(err, doc) { if (err) throw err; else console.log('save user successfully...'); console.log(User); //This is the problem }); 

代码工作正常,架构被加载到数据库中,但问题是我想打印刚添加到控制台窗口的架构。

在上面的代码中,我尝试过使用console.log(User) ,但是当我这样做的时候,我得到的是一堆我无法理解的行话。

如果我使用mongoterminal查询数据…

 db.users.find() 

我得到…

 { "_id" : "12345", "name" : "Help me!"} 

当我运行上面的代码时,这就是我想要打印到我的控制台窗口,我该怎么做?

要取回刚添加的文档,请尝试使用create()方法:

 var Schema = new mongoose.Schema( name: String, _id: String }), User = mongoose.model('User', Schema), obj = { name: "Help me!", _id: "12345" }; User.create(obj, function(err, user) { if (err) throw err; else console.log('save user successfully...'); console.log(user); //This is the solution }); 

您是控制台logging用户模型,而不是您创build的用户的实例。 尝试console.log(doc); 而是看到刚刚创build的新文档。