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