在我的代码中,我动态地插入了一个集合,而这个集合的默认值是
_id:ObjectId("5ed0d4d3fec27620043ee59d")
__v:0
我想这是mongodb中默认插入的,实际上我不需要这样,我试图删除这两个_id和__:0,但没有成功。
下面是我的代码。
var NewModel = require(path.resolve('./models/newmodelschema.model.js'))(collectionName);
NewModel.create({}, function(err, doc) {
NewModel.remove({_id:'',__v:0}, function(err) {
if (!err) {
console.log(err);
return;
} else {
console.log("Model empty");
}
});
});
你可以在创建模式时使用选项{ _id: false, versionKey: false }禁用_id和_v。
例如
const NewModel = new mongoose.Schema({
"name": { type: string}
}, { _id: false, versionKey: false });
NewModel.create({ "name": "foo"}, function(err, doc){
console.log("data ", doc);
});
应该能打印出来。
data { "name": "foo" }
没有_id和_v
编辑2:你不能删除_id,除非它是一个子文档。
PS:我建议保持这两点,要知道这些字段请阅读以下内容 https:/docs.mongodb.commanualcoredocument#the-id-field。 和 https:/mongoosejs.comdocsguide.html#versionKey