在 Mongoose 中保存对象后如何获取 objectID? [英] How do I get the objectID after I save an object in Mongoose?
本文介绍了在 Mongoose 中保存对象后如何获取 objectID?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
var n = new Chat();
n.name = "chat room";
n.save(function(){
//console.log(THE OBJECT ID that I just saved);
});
我想在 console.log 中记录我刚刚保存的对象的对象 ID.我如何在猫鼬中做到这一点?
I want to console.log the object id of the object I just saved. How do I do that in 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,它运行良好,再次运行以确保.
I'm on mongoose 1.7.2 and this works just fine, just ran it again to be sure.
这篇关于在 Mongoose 中保存对象后如何获取 objectID?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文