Node.js mongoose find() 方法使用对象中的键值

SS-*_*obi 1 mongoose mongodb node.js mongodb-schema

我想使用 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});
Run Code Online (Sandbox Code Playgroud)

我尝试的是

Newcontract.find({contractInfo: {userid: {$eq: req.body.userid}}})
Run Code Online (Sandbox Code Playgroud)

但我无法根据contractInfo对象中的这个userid获取数据

怎么做?

谢谢

J.F*_*.F. 6

您没有正确查询。

你需要这样的东西:

db.collection.find({
  "contractInfo.userid": "yourid"
})
Run Code Online (Sandbox Code Playgroud)

Mongo 游乐场示例在这里

将会mongoose非常相似:

Newcontract.findOne({
  "contractInfo.userid": req.body.id
})
Run Code Online (Sandbox Code Playgroud)

findOne()请注意,如果需要,您可以仅获取一个对象。