TIM*_*MEX 68 mongoose mongodb node.js
var n = new Chat();
n.name = "chat room";
n.save(function(){
//console.log(THE OBJECT ID that I just saved);
});
Run Code Online (Sandbox Code Playgroud)
我想在console.log中保存我刚刚保存的对象的对象id.我如何在Mongoose中做到这一点?
Ric*_*and 104
这对我有用:
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
$
Run Code Online (Sandbox Code Playgroud)
我正在使用mongoose 1.7.2并且这个工作正常,只是再次运行以确定.
Ana*_*ued 38
Mongo将完整的文档作为回调对象发送,因此您只需从那里获取它.
例如
n.save(function(err,room){
var newRoomId = room._id;
});
Run Code Online (Sandbox Code Playgroud)
小智 9
您可以在创建新对象实例后立即在 Mongoose 中获取对象 ID,而无需将其保存到数据库中。
我在 mongoose 4 中使用此代码工作。您可以在其他版本中尝试。
var n = new Chat();
var _id = n._id;
Run Code Online (Sandbox Code Playgroud)
或者
n.save((function (_id) {
return function () {
console.log(_id);
// your save callback code in here
};
})(n._id));
Run Code Online (Sandbox Code Playgroud)
您可以手动生成_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
Run Code Online (Sandbox Code Playgroud)
小智 5
其他答案提到添加回调,我更喜欢使用 .then()
n.name = "chat room";
n.save()
.then(chatRoom => console.log(chatRoom._id));
Run Code Online (Sandbox Code Playgroud)
文档中的示例:
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");
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
77015 次 |
| 最近记录: |