在Mongoose中保存对象后,如何获取objectID? [英] How do I get the objectID after I save an object in Mongoose?

查看:322
本文介绍了在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
$

我使用的是猫鼬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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆