![](/img/trans.png)
[英]Mongoose MongoDB find the one with smallest array-length of an array-field
[英]Why does this array-field query fail in Mongoose but not Mongo shell?
這是我在Mongoose中的User
模式。
var userSchema = mongoose.Schema({
username: {
type: String,
unique: true,
required: true
},
password: {
type: String,
required: true
},
mobile: {
type: Number,
required: true
},
accounts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Account'
}]
});
var User = mongoose.model('User', userSchema);
在mongo shell中,這將找到我現有的用戶文檔:
db.users.find({ accounts:"57d03b30edfd30e806fb20c9"})
但是,對於貓鼬,這會找到空集:
User.find({ accounts: "57d03b30edfd30e806fb20c9" })
.exec(function (err, users) {
*** users == [] ***
});
User.find({ accounts: mongoose.Types.ObjectId("57d03b30edfd30e806fb20c9") })
或者...
var ObjectId = mongoose.Types.ObjectId;
User.find({ accounts: ObjectId("57d03b30edfd30e806fb20c9") })
如@ vdj4y所述,Mongoose將您的查詢解釋為字符串而不是ObjectId(我想是嗎?)
實際上,如果架構匹配,則應將ObjectId視為字符串
accounts: [{
type: mongoose.Schema.Types.ObjectId,
ref: 'Account'
}]
然后像字符串一樣查詢
User.find({ accounts: "57d03b30edfd30e806fb20c9" })
.exec(function (err, users) {
*** users == [] ***
});
但是您需要刪除上一個條目,因為它當前是“混合”類型。 我猜混合實際上只是一個字符串,因此您可以嘗試使用如下所示的字符串類型。 好吧,您可以在mongoshell中查詢字符串並找到結果這一事實
accounts: [{
type: mongoose.Schema.Types.String,
ref: 'Account'
}]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.