首页 > 解决方案 > 已解决: find({user: {user: admin}}) 不适用于 mongodb

问题描述

我创建了一个小 API,我希望在登录 API 时仅使用用户名恢复用户配置文件,我的 Schema 看起来像这样(我使用 Mongoose):

user : {
  username: String,
  password: String
}

但是当我尝试执行时:

const User = require('../models/User')
const mongoose = require("mongoose")
User.find({user: {username: "test"})

它不起作用!我试试这个:

User.find({_id: "id")

和作品!我不明白 !

请帮帮我 !

标签: node.jsmongodbmongoose

解决方案


您可以使用点符号来查找值。

检查这个查询完美运行的例子

db.collection.find({
  "user.username": "test"
})

而且,为什么使用该对象不起作用?因为 mongo 试图寻找整个对象相等。

检查this example where using the object of the document is found (因为所有属性都在查询中使用)


推荐阅读