var n = new Chat();
n.name = "chat room";
n.save(function(){
//console.log(THE OBJECT ID that I just saved);
});
我想控制台记录我刚刚保存的对象的对象 ID。如何在 Mongoose 中做到这一点?
最佳答案
这对我有用:
var mongoose = require('mongoose'),
Schema = mongoose.Schema;
mongoose.connect('mongodb://localhost/lol', function(err) {
if (err) { console.log(err) }
});
var ChatSchema = new Schema({
name: String
});
mongoose.model('Chat', ChatSchema);
var Chat = mongoose.model('Chat');
var n = new Chat();
n.name = "chat room";
n.save(function(err,room) {
console.log(room.id);
});
$ node test.js
4e3444818cde747f02000001
$
我在 mongoose 1.7.2 上运行良好,只是再次运行它以确保。
https://stackoverflow.com/questions/6854431/