我创建了一个这样的对象:
var TodoItem = mongoose.model('TodoItem',
new mongoose.Schema({
title: String,
description: String
}));
var n = new TodoItem();
n.description = req.body.description;
n.title = req.body.title;
n.done = false;
n.save(function (err, todoitem) {
//todoitem._id does not work, I have to do todoitem._doc._id
}
为什么我不能直接在todoitem上访问保存对象?
答案 0 :(得分:2)
当mongoose返回对象时,它具有一些其他丰富的属性。在创建模式时使用选项toJSON / toObject或使用下面的代码:
回答1
var omitPrivate = function(doc, item) {
delete item.id;
delete item.__v;
return item;
};
// options
var options = {
toJSON: {
virtuals: true,
transform: omitPrivate
},
toObject: {
virtuals: true,
transform: omitPrivate
}
};
var TodoItem = mongoose.model('TodoItem',
new mongoose.Schema({
title: String,
description: String
},options));
var n = new TodoItem();
n.description = req.body.description;
n.title = req.body.title;
n.done = false;
n.save(function (err, todoitem) {
console.log(todoitem.toJSON());
})
回答2
var n = new TodoItem();
n.description = req.body.description;
n.title = req.body.title;
n.done = false;
n.save(function (err, todoitem) {
todoitem = JSON.parse(JSON.stringify(todoitem));
console.log(todoitem._id);
})