我正在尝试使用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
});
答案 0 :(得分:0)
您可以在调用模型构造函数时指定模式中使用的类型。
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
});