Javascript 使用“填充”显示用户名而不是id
我正在使用mongoosejs运行Expressjs,我在集合CustomerId之间建立了连接,如下所示:Javascript 使用“填充”显示用户名而不是id,javascript,mongodb,express,mongoose,Javascript,Mongodb,Express,Mongoose,我正在使用mongoosejs运行Expressjs,我在集合CustomerId之间建立了连接,如下所示: . . /** * Customer Schema */ var CustomerSchema = new Schema({ id : Number, name: String, joined: { type: Date, default: Date.now }, city: String }); mongoose.model('Customer', C
.
.
/**
* Customer Schema
*/
var CustomerSchema = new Schema({
id : Number,
name: String,
joined: { type: Date, default: Date.now },
city: String
});
mongoose.model('Customer', CustomerSchema);
.
.
/**
* Order Schema
*/
var OrderSchema = new Schema({
id : Number,
products: [Schema.Types.Mixed],
total: Number,
comments: String,
customerId: {type: Number, ref: 'Customer'}
});
mongoose.model('Order', OrderSchema);
.
.
exports.customerOrders = function (req, res) {
return Order.find({customerId: req.params.customerId}, function (err, orders) {
Order.populate(orders, {path: 'customerId', model: 'Order'}, function (err, orders) {
if (!err) {
return res.json(orders);
} else {
return res.send(err);
}
});
});
};
上述代码生成以下错误:
{
message: "Cast to ObjectId failed for value "1" at path "_id"",
name: "CastError",
type: "ObjectId",
value: 1,
path: "_id"
}
对象之间的关系是id
no\u id
请帮助我以正确的方式使用填充方法
Thanx,Mongoose的
填充功能仅支持使用\u id
字段查找引用集合中的相关文档
因此,您不能使用另一个字段,如id
,您需要将customerId
更改为:
customerId: {type: ObjectId, ref: 'Customer'}
在OrderSchema
中,然后用客户的\u id
值填充它。Hi@ya,删除了我放的内容,再看一眼,我认为您实际需要的是在customerId:{type:Number,ref:'customer'}
成为customerId:{type:mongoose.Types.ObjectId,ref:'customer'}
其中mongoose
是您给出的名称,例如-var mongoose=require('mongoose')代码>否,我没有引用ObjectId,我引用的是自定义数字字段,因此对象与数字连接可能值得一看-stackoverflow.com/questions/15771470/mongoose-cast-to-ObjectId-failed-for-valueI我使用id字段引用了相关对象,但没有使用populate(),我希望从第一个开始就使用populate())要显示customer.name而不是customer.id,但仍要使用id链接相关对象,有什么想法吗?