如何在mongodb中将aggregate用于$match\u id
文件:如何在mongodb中将aggregate用于$match\u id,mongodb,Mongodb,文件: { "_id" : ObjectId("560c24b853b558856ef193a3"), "name" : "Karl Morrison", "pic" : "", "language" : ObjectId("560c24b853b558856ef193a2"), "cell" : 1, "local" : { "email" : "karl.morrison@instanty.se", "passw
{
"_id" : ObjectId("560c24b853b558856ef193a3"),
"name" : "Karl Morrison",
"pic" : "",
"language" : ObjectId("560c24b853b558856ef193a2"),
"cell" : 1,
"local" : {
"email" : "karl.morrison@instanty.se",
"password" : "12345"
},
"sessions" : [
{
"id" : ObjectId("560c24b853b558856ef193a5")
}
]
}
这项工作:
yield new Promise(function (resolve, reject) {
users.col.aggregate([
{
$match: {
'name': 'Karl Morrison'
}
}
],
function (err, res) {
console.log('err ' + err);
console.log('res ' + JSON.stringify(res)); // <-- echos the object retrieved
if (err === null)
resolve(res);
reject(err);
});
});
产生新的承诺(函数(解析、拒绝){
users.col.aggregate([
{
$match:{
“姓名”:“卡尔·莫里森”
}
}
],
函数(err、res){
console.log('err'+err);
console.log('res'+JSON.stringify(res));//使用toString()方法
试试这个
const User = require('User')
const mongoose = require("mongoose");
User.aggregate([
{
$match: { _id: new mongoose.Types.ObjectId('560c24b853b558856ef193a3') }
}
])
\u id
必须是一个ObjectId
。Monk与.aggregate()
一起使用时,无法从字符串为您强制转换类型,因此您需要自己强制转换类型。可能重复。基本原因相同,即“自己强制转换”,因为两个框架都使用类似的代码进行自动转换,但没有一个适用于.aggregate()
@BlakesSeven确实,谢谢,它已经找了很久了(可能是因为猫鼬的缘故,所以没有找到它)如果我使用新的ObjectId而不是仅仅使用ObjectId会有问题吗?谢谢一帮人。mongoose.Types.ObjectId拯救了我的一天。天哪,这为我节省了宝贵的时间,谢谢有人知道为什么要为match指定ObjectId,为find你可以做MyModel.find({destination:myDestination.id})之类的事情吗直接的???提前谢谢你这不是与正确的做法相反吗?thnx!!这一个对我有用
const ObjectId = mongoose.Types.ObjectId;
const User = mongoose.model('User')
User.aggregate([
{
$match: { _id: ObjectId('560c24b853b558856ef193a3') }
}
])
const User = mongoose.model('User')
User.aggregate([
{
$match: { _id: user_id.toString() }
}
]
const User = require('User')
const mongoose = require("mongoose");
User.aggregate([
{
$match: { _id: new mongoose.Types.ObjectId('560c24b853b558856ef193a3') }
}
])