我已经使用像这样的猫鼬定义了一个模型:
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访问此对象时,检索的对象不是这样的doc,而是包装器:
这段代码......
// 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未定义.
这是为什么造成的?
这正是mongoose的目的,包装mongo对象.它提供了在文档上调用mongoose方法的功能.如果您想要简单的对象,如果您不打算在其上使用任何猫鼬魔法,您可以调用.toObject()
或使用精简查询.话虽这么说,平等检查应该仍然作为doc.password
回报doc._doc.password
.