【问题标题】:How do you change the _id from ObjectID to Number in Mongoose如何在 Mongoose 中将 _id 从 ObjectID 更改为 Number
【发布时间】:2017-07-22 17:15:56
【问题描述】:

我正在尝试使用 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

});

【问题讨论】:

标签: node.js mongodb mongoose


【解决方案1】:

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

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    
});

【讨论】:

  • 如果我做对了,你能检查我更新的问题吗?
  • Book 的架构是什么样的?例如mongoose.model('Book', {..?..});
  • 它是正确的,只是它的架构是 newID 而不是 Book
  • 当你不断改变问题时,很难知道你在问什么 - 请显示完整的代码,详细说明什么不工作以及你收到的任何错误消息 - 尽管如果你只需尝试我在答案中输入的内容,它就会起作用。我刚试过 - 它有效:)
  • 不客气 - 您可能想在下一个问题之前先阅读一下;) - stackoverflow.com/help/how-to-ask
猜你喜欢
  • 2018-06-25
  • 2017-10-09
  • 2014-07-16
  • 1970-01-01
  • 2021-03-18
  • 2022-01-19
  • 1970-01-01
  • 2021-11-30
  • 1970-01-01
相关资源
最近更新 更多