如何在Mongoose中设置_id到db文件?
我试图通过计算数据库中的文档,并使用该数字来创build_id(假设第一个_id为0),dynamic地为我的Mongoose模型创build_id。 但是,我无法从我的价值观中获得_id。 这是我的代码:
//Schemas var Post = new mongoose.Schema({ //_id: Number, title: String, content: String, tags: [ String ] }); var count = 16; //Models var PostModel = mongoose.model( 'Post', Post ); app.post( '/', function( request, response ) { var post = new PostModel({ _id: count, title: request.body.title, content: request.body.content, tags: request.body.tags }); post.save( function( err ) { if( !err ) { return console.log( 'Post saved'); } else { console.log( err ); } }); count++; return response.send(post); });
我试图设置_id许多不同的方式,但它不适合我。 这是最新的错误:
{ message: 'Cast to ObjectId failed for value "16" at path "_id"', name: 'CastError', type: 'ObjectId', value: 16, path: '_id' }
如果你知道发生了什么,请告诉我。
您需要将_id
属性声明为模式的一部分(您已将其注释掉),或者使用_id
选项并将其设置为false
(您正在使用id
选项,该选项创build一个虚拟getter将_id
转换为string但仍然创build了一个_id
ObjectID属性,因此铸造错误,你会得到)。
所以要么这个:
var Post = new mongoose.Schema({ _id: Number, title: String, content: String, tags: [ String ] });
或这个:
var Post = new mongoose.Schema({ title: String, content: String, tags: [ String ] }, { _id: false });
第一件@ robertklep的代码不适合我(mongoose4),也需要禁用_id
var Post = new mongoose.Schema({ _id: Number, title: String, content: String, tags: [ String ] }, { _id: false });
这对我有用
- 在与现有NodeJS应用程序相同的AWS EC2实例上安装MongoDB?
- 节点js for-loop在下次迭代之前等待asynchronous函数?
- 尝试使用Express在localhost:3000上运行脚本
- 在sails中创buildUTC时间戳而不会覆盖“createdAt”和“updatedAt”
- 在node.js“request.on”中是什么这个“.on”
- 在NodeJS / ExpressJS中创buildHTTP请求
- 这是什么时间格式,我如何将其转换为时代?
- build议使用需要编译的静态资产去项目结构和项目的构build系统?
- findOneAndUpdate与returnNewDocument一起使用:true返回原始文档MongoDB