var n = new Chat();
n.name = "chat room";
n.save(function(){
//console.log(THE OBJECT ID that I just saved);
});
我要console.log我刚刚保存的对象的对象ID。我该如何在猫鼬中做到这一点?
Answers:
这只是为我工作:
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,它工作正常,请确保再次运行。
您可以手动生成_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
其他答案提到添加回调,我更喜欢使用.then()
n.name = "chat room";
n.save()
.then(chatRoom => console.log(chatRoom._id));
来自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");
});
有了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;
// ...
});
实际上,实例化对象时,ID应该已经存在
var n = new Chat();
console.log(n._id) // => 4e7819d26f29f407b0... -> ID is already allocated
在此处检查此答案:https : //stackoverflow.com/a/7480248/318380