首先,使用 Mongoose 模型创建数据库模式。在此模式中,应该包含字段的 ObjectId,用于与其他字段进行比较。
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const mySchema = new Schema({
field1: {
type: String,
required: true
},
field2: {
type: String,
required: true
},
relatedField: {
type: Schema.ObjectId,
ref: 'OtherModel',
required: true
}
});
module.exports = mongoose.model('MyModel', mySchema);
然后,使用 Mongoose 提供的 populate 方法在查询期间填充相关字段模型。
const MyModel = require('./myModel');
MyModel.find()
.populate('relatedField')
.exec(function(err, data) {
if (err) {
console.log('Error:', err);
return;
}
console.log('Data:', data);
});
在这里,我们使用 populate
方法填充 relatedField
,它代表其他模型的 ObjectId。
最后,我们可以使用 find
方法来比较字段的 ObjectId,并列出满足条件的特定数据。
MyModel.find({ relatedField: someOtherObjectId })
.exec(function(err, data) {
if (err) {
console.log('Error:', err);
return;
}
console.log('Data:', data);
});
在这里,我们使用 find
方法来找到与 someOtherObjectId
匹配的数据。
这样,我们就可以比较字段的 ObjectId 并显示特定数据了。
上一篇:比较一个字典列表和一个列表
下一篇:比较一个字符变量和一个时间戳