node.js - 你如何在 Mongoose 中将 _id 从 ObjectID 更改为 Number

标签 node.js mongodb mongoose

我正在尝试使用 mongoose js 程序进行插入,但是我想使用 1、2、3、4 等作为 ID,而不是使用为我自动创建的 BSON ObjectID。

var mongoose = require('mongoose');

var dbHost = 'mongodb://localhost:27017/mong_db';

//var newID = mongoose.model('bookSchema', { _id: Number, name: String });

 mongoose.connect(dbHost);

 //Create a schema for Book

  var bookSchema = mongoose.Schema({

  _ id: Number, 

  name: String,

  //Also creating index on field isbn

  isbn: {type: String, index: true},

  author: String,

   pages: Number

  });

>Updated 


var book1 = new Book({

 _id = 1
name:"Mongoose Demo 1",

isbn: "MNG123",

author: "Author1,  Author2",

pages: 123

});

最佳答案

您可以在调用模型构造函数时指定模式中使用的类型。

var Cat = mongoose.model('Cat', { _id: Number, name: String });

然后在存储对象时传入一个_id字段。

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test-mongo-id');

var Cat = mongoose.model('Cat', { _id: Number, name: String });

var kitty = new Cat({ _id: 1, name: 'Zildjian' });
kitty.save(function (err) {
  console.log(err || 'meow');
  Cat.findOne({_id: 1}, function (err, cat) {
    console.log(err || 'Cat:', cat)
  });
});

输出:

meow
Cat: { _id: 1, name: 'Zildjian', __v: 0 }

你的模式应该有 _id: Number 像这样:

var bookSchema = mongoose.Schema({
  _id: Number,    // <-- You're missing this
  name: String,    
  //Also creating index on field isbn    
  isbn: {type: String, index: true},    
  author: String,    
  pages: Number    
});

关于node.js - 你如何在 Mongoose 中将 _id 从 ObjectID 更改为 Number,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42564578/

相关文章:

node.js - 在 Node.js 上使用非阻塞操作响应请求处理程序

node.js - 使用事务时,查询中包含的子查询如何在 pg-promise 中工作?

mongodb - 如何配置 Crafter CMS 社交/个人资料 mongo db 连接属性?

node.js - NodeJS MongoDB : Querying ISO Date

node.js - MongoDB $addFields 和 $in 总计

node.js - Hapi-Swagger 因 header 值而失败

node.js - NowJS 当前 session

javascript - 如何使用 multer-gridfs-storage、express、mongodb 在用户配置文件中添加图像路径

javascript - 动态定义 Mongoose 模型方法

node.js - 使用 Mongoose 库更新 Express JS 中的数据库架构