在多个字段上使用mongoose findById()?
我有一个像这样的模型在多个字段上使用mongoose findById()?,mongoose,Mongoose,我有一个像这样的模型 var mongoose = require('mongoose'); var tableSchema = new mongoose.Schema({ version: { type: String, uppercase: true , required: true, trim: true }, name: { type: String, uppercase: true , required: true, trim: true }, descr: S
var mongoose = require('mongoose');
var tableSchema = new mongoose.Schema({
version: { type: String, uppercase: true , required: true, trim: true },
name: { type: String, uppercase: true , required: true, trim: true },
descr: String
});
uctableSchema.index({ version: 1, name: 1 }, { unique: true });
module.exports = mongoose.model('Table', tableSchema);
> db.tables.findOne()
{
"_id" : ObjectId("56fc97d6e81ed6faf5e75b58"),
"version" : "4",
"name" : "address",
"descr" : "contact address table"
}
此模型将生成如下集合
var mongoose = require('mongoose');
var tableSchema = new mongoose.Schema({
version: { type: String, uppercase: true , required: true, trim: true },
name: { type: String, uppercase: true , required: true, trim: true },
descr: String
});
uctableSchema.index({ version: 1, name: 1 }, { unique: true });
module.exports = mongoose.model('Table', tableSchema);
> db.tables.findOne()
{
"_id" : ObjectId("56fc97d6e81ed6faf5e75b58"),
"version" : "4",
"name" : "address",
"descr" : "contact address table"
}
没关系。我故意离开猫鼬来生成自动识别码
我创建了一个唯一的复合索引作为主键
数据实际上是通过json文件从RDBMS导入的。因此mongoimport将自动为其生成_id。那很好
_id值没有实际意义,我希望通过复合主键检索、修改和删除数据
在我的情况下,我仍然可以使用findById吗
Model.findById(id, [projection], [options], [callback])
Model.findByIdAndUpdate(id, [update], [options], [callback])
Model.findByIdAndRemove(id, [options], [callback])
我知道第一个参数id指的是我不想使用的_id
是否有办法使id参数引用我的复合密钥、版本和名称?或者我不应该在我的情况下使用findById
谢谢,不,xxxById方法都是专为使用
\u id
而设计的
例如,以下是findById
的源代码:
Model.findById=函数findById(id、投影、选项、回调){
如果(id的类型=='undefined'){
id=null;
}
返回this.findOne({u id:id},投影,选项,回调);
};
您需要使用更通用的findOne
、findOneAndUpdate
和findOneAndRemove
方法