我正在运行mongod,并尝试将数据保存在集合中。我定义了
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Person = new Schema({
id: Number,
name:String
},{ collection: 'customers' });
module.exports = mongoose.model('Person', Person);
但是后来,当我想保存数据时,例如
var p = new Person({
id:1,
name:"John"
});
p.save(function(err,doc){
if(err){
console.log(err)
}
}
它会抛出错误
消息:'E11000重复键错误集合:人员索引:id_-1 dup key:{:1}',
但在蒙戈,当我做的时候
db.Person.count() // returns 0
show collections // nothing
表示数据没有甜菜保存insid db。为什么它一直在抛出关于重复密钥的错误?
答案 0 :(得分:0)
在Mongoose模式中,id
字段是特殊的(它是_id
字段的字符串表示形式。)
您应该将其命名为_id
,或者您可以将其删除,_id
隐含在那里。然后在创建新对象时使用_id
。
示例:
var mongoose = require('mongoose');
var Schema = mongoose.Schema;
var Person = new Schema({
name:String
},{ collection: 'customers' });
module.exports = mongoose.model('Person', Person);
var p = new Person({
_id:1,
name:"John"
});
p.save(function(err,doc){
if(err){
console.log(err)
}
}
或者你不必写id,它是隐式自动生成的
var p = new Person({
name:"John"
});
p.save(function(err,doc){
if(err){
console.log(err)
}
}