【问题标题】:How to find locations of a single user in mongodb?如何在mongodb中查找单个用户的位置?
【发布时间】:2020-10-01 15:53:13
【问题描述】:

假设我有下面这两个模型,我想在节点中使用 mongoose 获取或获取特定用户的位置:

用户模型

const userSchema = new mongoose.Schema({
name: {
    type: String,
    minlength: 2,
    maxlength: 50,
},
email: {
    type: String,
    minlength: 5,
    maxlength: 255,
    unique: true,
},
password: {
    type: String,
    minlength: 5,
    maxlength: 1024,
},
});

位置模型

const locationtSchema = new mongoose.Schema({
name: {
    type: String,
    minlength: 5,
    maxlength: 50,
},
lat: {
    type: String,
    required: true,
},
lng: {
    type: String,
    required: true,
},
user: {
    type: userSchema,
    required: true,
},
});

所以,我试着像这样解决它......但它没有用。

const location = Location.find({
    'user._id': req.params._id
})

如何返回特定用户的位置?

【问题讨论】:

  • 导入 ObjectId 并尝试以下操作: const location = Location.find({ 'user._id': new Objectid(req.params._id) });这应该可以正常工作!

标签: javascript node.js mongodb mongoose mongoose-schema


【解决方案1】:

您尝试传递的 id 是一个字符串,而应该是一个对象 id

const location = Location.find({
    'user._id': mongoose.Types.ObjectId(req.params._id)
})

现在可以完美运行了。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-27
    • 2016-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-18
    相关资源
    最近更新 更多