在 Mongoose 中保存对象后如何获取 objectID?

发布于 2024-11-26 12:02:54 字数 194 浏览 1 评论 0原文

var n = new Chat();
n.name = "chat room";
n.save(function(){
    //console.log(THE OBJECT ID that I just saved);
});

我想 console.log 我刚刚保存的对象的对象 ID。我该如何在猫鼬中做到这一点?

var n = new Chat();
n.name = "chat room";
n.save(function(){
    //console.log(THE OBJECT ID that I just saved);
});

I want to console.log the object id of the object I just saved. How do I do that in Mongoose?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

韵柒 2024-12-03 12:02:54

这对我有用:

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,它工作得很好,只需再次运行它即可确定。

This just worked for me:

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
$

I'm on mongoose 1.7.2 and this works just fine, just ran it again to be sure.

予囚 2024-12-03 12:02:54

Mongo 将完整文档作为回调对象发送,因此您只需从那里获取它即可。

例如

n.save(function(err,room){
  var newRoomId = room._id;
  });

Mongo sends the complete document as a callbackobject so you can simply get it from there only.

for example

n.save(function(err,room){
  var newRoomId = room._id;
  });
百变从容 2024-12-03 12:02:54

您可以手动生成 _id,这样您就不必担心稍后将其拉回。

var mongoose = require('mongoose');
var myId = mongoose.Types.ObjectId();

// then set it manually when you create your object

_id: myId

// then use the variable wherever

You can manually generate the _id then you don't have to worry about pulling it back out later.

var mongoose = require('mongoose');
var myId = mongoose.Types.ObjectId();

// then set it manually when you create your object

_id: myId

// then use the variable wherever
泼猴你往哪里跑 2024-12-03 12:02:54

创建新的对象实例后,您可以立即在 Mongoose 中获取对象 ID,而无需将其保存到数据库中。

我正在 mongoose 4 中使用此代码。您可以在其他版本中尝试。

var n = new Chat();
var _id = n._id;

或者

n.save((function (_id) {
  return function () {
    console.log(_id);
    // your save callback code in here
  };
})(n._id));

You can get the object id in Mongoose right after creating a new object instance without having to save it to the database.

I'm using this code work in mongoose 4. You can try it in other versions.

var n = new Chat();
var _id = n._id;

or

n.save((function (_id) {
  return function () {
    console.log(_id);
    // your save callback code in here
  };
})(n._id));
夢归不見 2024-12-03 12:02:54

其他答案提到添加回调,我更喜欢使用

n.name = "chat room";
n.save()
.then(chatRoom => console.log(chatRoom._id));

文档 中的 .then() 示例: 。

var gnr = new Band({
  name: "Guns N' Roses",
  members: ['Axl', 'Slash']
});

var promise = gnr.save();
assert.ok(promise instanceof Promise);

promise.then(function (doc) {
  assert.equal(doc.name, "Guns N' Roses");
});

Other answers have mentioned adding a callback, I prefer to use .then()

n.name = "chat room";
n.save()
.then(chatRoom => console.log(chatRoom._id));

example from the docs:.

var gnr = new Band({
  name: "Guns N' Roses",
  members: ['Axl', 'Slash']
});

var promise = gnr.save();
assert.ok(promise instanceof Promise);

promise.then(function (doc) {
  assert.equal(doc.name, "Guns N' Roses");
});
毅然前行 2024-12-03 12:02:54

好吧,我有这个:

TryThisSchema.post("save", function(next) {
    console.log(this._id);
});

注意第一行中的“post”。使用我的 Mongoose 版本,保存数据后获取 _id 值没有任何问题。

Well, I have this:

TryThisSchema.post("save", function(next) {
    console.log(this._id);
});

Notice the "post" in the first line. With my version of Mongoose, I have no trouble getting the _id value after the data is saved.

帅冕 2024-12-03 12:02:54

实际上,在实例化对象时,ID 应该已经存在,

var n = new Chat();
console.log(n._id) // => 4e7819d26f29f407b0... -> ID is already allocated

请在此处检查此答案: https://stackoverflow.com/a/7480248/318380< /a>

Actually the ID should already be there when instantiating the object

var n = new Chat();
console.log(n._id) // => 4e7819d26f29f407b0... -> ID is already allocated

Check this answer here: https://stackoverflow.com/a/7480248/318380

貪欢 2024-12-03 12:02:54

根据 Mongoose v5.x 文档:

save() 方法返回一个承诺。如果 save() 成功,
Promise 解析为已保存的文档。

使用它,类似这样的事情也可以工作:

let id;
    
n.save().then(savedDoc => {
    id = savedDoc.id;
});

As per Mongoose v5.x documentation:

The save() method returns a promise. If save() succeeds, the
promise resolves to the document that was saved.

Using that, something like this will also work:

let id;
    
n.save().then(savedDoc => {
    id = savedDoc.id;
});
悲欢浪云 2024-12-03 12:02:54

使用save,您只需要做的是:

n.save((err, room) => {
  if (err) return `Error occurred while saving ${err}`;

  const { _id } = room;
  console.log(`New room id: ${_id}`);

  return room;
});

以防万一有人想知道如何使用create获得相同的结果:

const array = [{ type: 'jelly bean' }, { type: 'snickers' }];

Candy.create(array, (err, candies) => {
  if (err) // ...

  const [jellybean, snickers] = candies;
  const jellybeadId = jellybean._id;
  const snickersId = snickers._id;
  // ...
});

查看官方文档

With save all you just need to do is:

n.save((err, room) => {
  if (err) return `Error occurred while saving ${err}`;

  const { _id } = room;
  console.log(`New room id: ${_id}`);

  return room;
});

Just in case someone is wondering how to get the same result using create:

const array = [{ type: 'jelly bean' }, { type: 'snickers' }];

Candy.create(array, (err, candies) => {
  if (err) // ...

  const [jellybean, snickers] = candies;
  const jellybeadId = jellybean._id;
  const snickersId = snickers._id;
  // ...
});

Check out the official doc

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文