提问者:小点点

node.js mongoose find()方法在对象中具有键值的用法


我想使用find()函数从mongodb中查找数据这里是我的模式

  const newcontractSchema = mongoose.Schema({
  creator: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: false,
    index: true,
  },
  status: {type: String, required: false, default: 'init'},
  a_status: {type: String, required: false, default: 'pending'},

  contractInfo: {
    startDate: {type: Date},
    endDate: {type: Date},
    expectedUsage: {type: Number, default: 2000},
    provider: {type: Object},
    rate: {type: Number},
    term: {type: Number},
    userid: {type: String}


}, {timestamps: true});

我试过的是

Newcontract.find({contractInfo: {userid: {$eq: req.body.userid}}})

但我无法在contractInfo对象中提取基于此用户ID的数据

怎么做?

谢谢


共1个答案

匿名用户

您的查询不正确。

你需要这样的东西:

db.collection.find({
  "contractInfo.userid": "yourid"
})

Mongo playground示例如下

猫鼬中会非常类似:

Newcontract.findOne({
  "contractInfo.userid": req.body.id
})

注意,如果需要,可以使用findone()只获取一个对象。