一尘不染

Model.findOne不返回文档,但返回包装对象

node.js

我用如下猫鼬定义了一个模型:

var mongoose = require("mongoose")
var Schema = mongoose.Schema

var userObject = Object.create({
    alias: String,
    email: String,
    password: String,
    updated: { 
        type: Date,
        default: Date.now
    }
})

var userSchema = new Schema(userObject, {strict: false})
var User = mongoose.model('User', userSchema)

module.exports = User

然后创建了一个用户,可以通过mongo控制台完美地找到它,如下所示:

db.users.findOne({ email: "coco@coco.com" });
{
    "_id" : ObjectId("55e97420d82ebdea3497afc7"),
    "password" : "caff3a46ebe640e5b4175a26f11105bf7e18be76",
    "gravatar" : "a4bfba4352aeadf620acb1468337fa49",
    "email" : "coco@coco.com",
    "alias" : "coco",
    "updated" : ISODate("2015-09-04T10:36:16.059Z"),
    "apps" : [ ],
    "__v" : 0
}

但是,当我尝试通过带有mongoose的node.js访问此对象时,要检索的对象不是此类文档,而是包装器:

这段代码…

// Find the user for which the login queries
  var User = require('../models/User')
  User.findOne({ email: mail }, function(err, doc) {
    if (err) throw err
      if (doc) {
        console.dir(doc)
        if(doc.password == pass) // Passwords won't match

从console.dir(doc)产生此输出…

{ '$__': 
   { strictMode: false,
     selected: undefined,
     shardval: undefined,
     saveError: undefined,
     validationError: undefined,
     adhocPaths: undefined,
     removing: undefined,
     inserting: undefined,
     version: undefined,
     getters: {},
     _id: undefined,
     populate: undefined,
     populated: undefined,
     wasPopulated: false,
     scope: undefined,
     activePaths: { paths: [Object], states: [Object], stateNames: [Object] },
     ownerDocument: undefined,
     fullPath: undefined,
     emitter: { domain: null, _events: {}, _maxListeners: 0 } },
  isNew: false,
  errors: undefined,
  _doc: 
   { __v: 0,
     apps: [],
     updated: Fri Sep 04 2015 12:36:16 GMT+0200 (CEST),
     alias: 'coco',
     email: 'coco@coco.com',
     gravatar: 'a4bfba4352aeadf620acb1468337fa49',
     password: 'caff3a46ebe640e5b4175a26f11105bf7e18be76',
     _id: { _bsontype: 'ObjectID', id: 'Uét Ø.½ê4¯Ç' } },
  '$__original_validate': { [Function] numAsyncPres: 0 },
  validate: [Function: wrappedPointCut],
  _pres: { '$__original_validate': [ [Object] ] },
  _posts: { '$__original_validate': [] } }

因此,密码将不匹配,因为doc.password未定义。

为什么会这样呢?


阅读 293

收藏
2020-07-07

共1个答案

一尘不染

这正是包裹猫鼬对象的猫鼬的目的。它提供了在文档上调用猫鼬方法的功能。如果您希望使用简单的对象,那么如果您根本不打算在其上使用任何猫鼬魔法,则可以调用.toObject()或使用精益查询。话虽如此,相等性检查仍应保留为doc.passwordreturn doc._doc.password

2020-07-07